vue2.0组件传值
vue是基于数据驱动,主要关注数据动态变化的过程即可。
先放完整代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app-5">
<p>{{ message }}</p>
<input v-model="message">
<button @click="reverseMessage">逆转消息</button>
<br>
<br>
<div>父组件所定义的值:<strong>{{parentMsg}}</strong></div>
<ol>
<!-- 创建一个 todo-item 组件的实例 -->
<todo-item :pmsg='parentMsg' :todo123='todo' ></todo-item>
<todo-item2 @communicate="childHandle" ></todo-item2>
</ol>
</div>
<p id="bus"></p>
</div>
<script>
// -----------------------------非父子组件之间传值--------------------------------------
// 需要定义个公共的实例对象Bus作为中间仓库来传值,不然组件之间达不到传值的效果。
const Bus = new Vue();
// data:{}和data(){return{}}区别在于后面这个this的使用
// 定义名为 todo-item 的子组件1
Vue.component('todo-item', {
//-------------------------------父组件值传递给子组件------------------------------------------
// <todo-item :pmsg='parentMsg' :todo='todo' ></todo-item>
// 先在 todo-item 标签上定义好要传递的值 parentMsg 和 todo,并赋予pmsg和todo123(名称随意)
// 子组件通过 props 接收父组件传递的值,子组件就可使用,但不可以更改.(vue单项传递数据原则)
props: ['pmsg','todo123'],
data(){
return{
msg:this.pmsg,
childMsg:'子组件1好多好多信息'
}
},
template: '<li><h3>子组件1</h3><p>{{ todo123.text }}</p><b>子组件2可改变的父组件值:{{ pmsg }}</b><button @click="communicate1">子组件1传递子组件2值</button></li>',
methods:{
communicate1(){
Bus.$emit('Busemit',this.childMsg)
}
}
})
// 定义名为 todo-item2 的子组件2
Vue.component('todo-item2',{
props:['todo'],
data(){
return{
childMsg:'子组件2信息'
}
},
template:'<li><h3>子组件2</h3><p>{{childMsg}}</p><button @click="communicate2">子传递父值</button></li>',
created() {
Bus.$on("Busemit", (msg)=>{
this.childMsg = msg;
});
},
methods:{
//-------------------------------子组件值传递给父组件------------------------------------------
communicate2(){
// <todo-item2 @communicate="childHandle" ></todo-item2>
// 点击触发communicate2函数
// 然后$emit todo-item2 标签上的communicate属性,此时触发父组件childHandle函数,并传递子组件2数据childMsg
this.$emit('communicate',this.childMsg);
}
}
})
var app5 = new Vue({
el: '#app-5',
data() {
return{
parentMsg:'我是父组件值',
message: 'Hello Vue.js!',
todo: {
text: "哈哈哈哈"
}
}
},
methods: {
reverseMessage () {
this.message = this.message.split('').reverse().join('')
},
childHandle(childMsg){
this.parentMsg = childMsg;
}
}
})
</script>
</body>
</html>
- vue2.0 组件化及组件传值
- VUE2.0 父组件传值给子组件初始化用
- vue2.0组件之间的传值
- vue2.0组件之间传值、通信的多种方式(干货)
- Vue2.0 子组件传值给父组件
- vue父子组件中传值
- vue2.0的组件
- Vue2.0的通用组件
- vue组件传值
- vue2.0父子组件间传递数据的方法
- vue2.0动态添加组件
- 基于vue2.0的活动倒计时组件countdown(附源码下载)
- Vue2.0组件间数据传递示例
- JavaScript中push()两层循环数据及多层,vue用iview(2.0+)UI 组件库时,制作级联全国地址下拉列表
- 基于 Vue2.0 的移动端 / PC 端验证码输入组件.
- vue2.0 之 douban (三)创建header组件
- Vue2.0基于vue-cli+webpack同级组件之间的通信教程(推荐)
- [js高手之路]Vue2.0基于vue-cli+webpack父子组件通信教程
- vue2.0 transition组件实现过渡效果
- vue 2.0组件与v-model详解