What this article brings to you is what are the value transfer methods of vue? An introduction to commonly used value-passing methods in Vue (3 types) has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
1. Parent component passes value to child component
1. Use props to establish a data channel
// 这是父组件 <div id="app"> // 这是子组件 <child message="hello" ></child> </div>
2. The data passed through props in the child component
Vue,component('child',{ props:['message'] })
2. The child component passes the value to the parent component
1. A click event is needed to trigger a custom event in the child component
Vue.component('child',{ methods:{ handleClick(){ // 在相应该点击事件的函数使用$emit来触发一个自定义事件,并传递一个参数 this.$emit('parentClick',123) } }, template:` <div> <h1>这是子组件</h1> <button @click="handleClick" > 发送给父组件 </button> </div> ` })
2. The child tag in the parent component listens to the custom event to get the passed value
Vue.component('parent', { data() { return { msg: '我是子组件' } }, methods: { receiveMsg(value) { console.log(value) this.msg = value } }, template:' <div> <h1>这是子组件</h1> <p>接收子组件传过来的值{{msg}}</p> <child @parentClick='receiveMsg'></child> </div> ' })
3. Non-parent-child component passing value
Sometimes two components also need to pass value (non-parent-child relationship), so we need a public vue to pass value and get value
1. Create An empty vue
// 创建一个空的公共的vue对象 var bus = new Vue();
2. In component 1, define $emit to send data
bus.$emit('test','数据')
3. Use $on in component 2 to receive the passed data
bus.$on('test', function(num) { this.msg= num; //事件的解绑问题 bus.$off("test") })
Of course there is more than one way to pass values from parent to child. We can also use localstorage to pass and get values.
// 在第一个组件中 setItem 设置值local storage.setItem('test','数据') // 在第二个组件中 getItem 获取值local Storage.getItem("test");
Related recommendations:
Value passing between vue components Way
#How does vue get the currently clicked element and pass the value
The above is the detailed content of What are the ways to pass values in Vue? Introduction to commonly used value passing methods in Vue (3 types). For more information, please follow other related articles on the PHP Chinese website!