您的位置:首页 > Web前端 > Vue.js

vue2.0组件传值

2019-01-16 17:14 295 查看

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>

 

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: