vue组件
一、全局组件
全局组件在注册之后可以在项目的任何模板中使用
全局注册的行为必须在根 Vue 实例 (通过 new Vue
) 创建之前发生
注册组件就是利用Vue.component()
方法,先传入一个自定义组件的名字,然后传入这个组件的配置。一般是在main.js注册
//注册全局组件
Vue.component('myComponent', { props:['name','age'],//这里可以写使用组件时传入的值 template: '<div>{{msg}},我是一个全局组件,我叫{{name}},我今年{{age}}</div>', data() { return { msg: 'hello world!' //这里可以写组件自定义的数据 } } })
//使用全局组件 可以传值
<myComponent name="lisa" age="23"></myComponent>
二、局部组件
//局部组件注册,写在实例的components中
components: { 'my-component': { props:['name','age'], template: `<div>{{msg}},这是一个局部的自定义组件,只能在当前Vue实例中使用,我叫{{name}},我今年{{age}}</div>`, data() { return { msg:'hi' } } } }
//局部组件使用 可以传值
<my-component name="luna" age="34"></my-component>
Prop 验证
我们可以为组件的 prop 指定验证要求,例如你知道的这些类型。如果有一个需求没有被满足,则 Vue 会在浏览器控制台中警告你。这在开发一个会被别人用到的组件时尤其有帮助。
Vue.component('my-component', { props: { // 基础的类型检查 (`null` 和 `undefined` 会通过任何类型验证) propA: Number, // 多个可能的类型 propB: [String, Number], // 必填的字符串 propC: { type: String, required: true }, // 带有默认值的数字 propD: { type: Number, default: 100 }, // 带有默认值的对象 propE: { type: Object, // 对象或数组默认值必须从一个工厂函数获取 default: function () { return { message: 'hello' } } }, // 自定义验证函数 propF: { validator: function (value) { // 这个值必须匹配下列字符串中的一个 return ['success', 'warning', 'danger'].indexOf(value) !== -1 } } } })
三、父子组件通信
子组件访问父组件数据:1:props通过父组件属性传值而取得父组件数据
2:直接获取 ,this.$parent.变量名
子组件可以修改父组件的变量,但是不能改props传的值
子组件调用父组件方法:1:this.$emit('响应事件', 参数); // eg:this.$emit('changePreFn', 1);
在父组件 <user1 @changePreFn="changeCount" :count="count" :message="hello" ref="user1"></user1> changeCount是写在父组件的方法
2:this.$parent.changeCount(11); //这种方法比上面的简单,更直接
父组件访问子组件的数据:this.$refs.user1.count
父组件调用子组件的方法:this.$refs.user1.childMeth(1);
这种通过$refs的方法需要在调用子组件的时候给子组件设置ref属性 //eg:<user1 ref="user1" :count="count" :message="hello" ></user1>