1.vue中 组件 就是模块化
Vue.component(‘组件名’, {对象}); //定义组件基本语法。
组件名: //驼峰式命名定义buttonContrller使用
Vue.component('buttonContrller', {
props: []; //给组件传参,数组类型
template: `<button>按钮</button>`
});
2.Vue组件其实就是一个vue实例,具备vue对象所有属性和方法,除了el属性。它是没有的。
Vue.component('buttonController', {
props: ['content','title'],
data: function () {
return {ok:100}
},
methods: {
okhandle: function () {
this.ok = 5;
},
showvalue: function () {
alert(this.title);
},
setcontent: function () {
//this.content = "子组件内部修改content的值";
//$emit 组件内置方法, 参数1: 触发事件名成 参数2 给事件箭筒函数传递的参数。
//this.$emit('content', "我是子组件给父组件传递的值");
}
},
template: `<div><h1 style="border:1px solid #f60;">
<span @click="showvalue">{{ok}}</span>
<button @click="setcontent">按钮</button>
<ul><li @click="okhandle">{{content}}</li></ul>
</h1>
<div>
<input v-model="content" style="height:30x; line-height:30px; border:1px solid green;">
<sub-controller></sub-controller></div></div> `
})
vue 父组件:
contentchange: function (value) {
//alert(value);
//this.msg = value;
},
setmsg: function () {
this.msg = '你好';
},
html页面
<div>{{msg}}</div>
<span @click="setmsg">动态更改子组件的值</span>
<button-controller v-bind:content.sync="msg" title="100"></button-controller>
<button-controller content="中国人民万岁" title="200"></button-controller>
3.父子组件之间,直接传递会有错误。(父子之间变量相互影响,使用中间变量代理一下即可)
htmlcontent: 就是中间代理.
props: ['content'],
data(){
return {htmlcontent: this.content}
},
template: '<textarea v-model="htmlcontent" @change="changetext"></textarea>',
methods: {
changetext() {
this.$emit('update:content', this.htmlcontent);
}
}