This article mainly introduces how to solve the two-way binding problem between Vue2. I am using UI components for my own use. To improve my BIG, I encountered a problem when making a component containing input: I don’t know how to achieve two-way binding between the input in the sub-component and the data of the caller (parent component). I thought about using Vuex, but I didn’t know how to use it. After looking at other excellent UI frameworks, I found that using Vuex would cause trouble to other users, so I decided to find a solution. After referring to several articles by experts, I finally found it.
I post the solution here, hoping to help colleagues like me who are coming into contact with the Vue framework for the first time.
The code logic of the child component<template>
<p class="ne-ipt">
<input type="text" v-model="currentValue">
</p>
</template>
<style lang="less" scoped>
@import "../../assets/styles/form/form.less";
</style>
<script>
export default {
name: 'NeIpt',
props: {
// 接收一个由父级组件传递过来的值
value: {
type: String,
default: function () {
return ''
}
}
},
computed:{
currentValue: {
// 动态计算currentValue的值
get:function() {
return this.value; // 将props中的value赋值给currentValue
},
set:function(val) {
this.$emit('input', val); // 通过$emit触发父组件
}
}
}
}
</script>
<template>
<p id="button-index">
<ne-ipt placeholder="姓名" v-model="test"></ne-ipt>
</p>
</template>
<style>
</style>
<script>
import NeIpt from './NeIpt'
export default {
name: 'form-index',
data () {
return {
test: ''
}
},
components: {
NeIpt
}
}
</script>
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
Use vue element-ui ajax technologies to implement an instance of a formvue registration component Several ways to summarizeVue.js custom event form input component methodThe above is the detailed content of About two-way binding of parent component and child component in Vue2.x (detailed tutorial). For more information, please follow other related articles on the PHP Chinese website!