1、vue组件
-
.vue组件中的data不能指向对象,是一个函数
-
vue组件包含:template、script、style
-
script中必须是export default{}
-
template只能有一个根节点,所以要先创建一个div,其他的标签都在这个div中
-
style中css一个样式包含另一个样式需要实现声明lang="less"
-
style默认是css语法
<template> <div> <div class="box"> <h3>这是第一个样式{{ username }}</h3> <button @click="changeName">修改用户名</button> </div> <div>123</div> </div> </template> <script> export default { data() { return { username: "zs" }; }, methods: { changeName() { this.username = "ls"; }, }, watch: {}, computed: {}, filters: {} }; </script> <style lang="less"> .box { background-color: pink; h3 { color: red; } } </style>
2、使用组件的三个步骤
(1)在根组件使用import语法导入需要的组件
(2)在根组件使用components节点注册组件
(3)在根组件以标签的形式使用刚才注册的组件
<script> //步骤1 import Left from '@/components/Left.vue' //步骤2 export default { components:{ Left } }; </script> <!--步骤3--> <div class="box"> <left></Left> </div>
3、Vue.component
(1)通过components注册的是私有子组件
(2)注册全局组件
在vue项目的main.js入口文件中,通过vue.component()方法,可以注册全局组件
import Count from '@/components/Count.vue' //注册名称 Vue.component('MyCount', Count)
4、组件的props
(1)概念:是组件的自定义属性,在封装通用组件时,合理地使用props可以极大提高组件的复用性
(2)语法:值指向数组
绑定的时候加上属性名
export default { props:['自定义属性1','自定义属性2','自定义属性n'], data() { return { }; }, };
(3)结合v-bind使用自定义属性
在调用的使用加上v-bind会使字符串转化为数字
<MyCount :init="9"></MyCount>
(4)props是只读的
自定义属性是只读的,程序员不能直接修改props的值,否则会报错,需要修改就将其转存到可以读写的属性中
(5)default默认值
外界没有传递属性值使用default的默认值
export default { props: { init: { default: 0, } } };
(6)type值类型
如果不是这个类型,终端会报错
export default { props: { init: { default: 0, type: Number, } } };
(7)required必填项
若不传值,即使有默认值也会报错
export default { props: { init: { default: 0, type: Number, required: true, } } };
5、样式冲突
(1)为了使一个vue组件的样式不再其他组件显示,解决方法:
-
使用[]选择器,给同一组件的标签都加一个属性
-
在style中加scoped属性
(2)/deep/样式穿透
-
由于有了scoped使得改变其他vue的样式不好用,因此使用/deep/
-
使用组件库时修改样式也会用到/deep/
<style lang="less" scoped> /deep/ h5 { color: purple; } </style>