方法一
父组件用.sync修饰,子组件通过$emit('update:参数',值)函数去修改。在项目中通常可以用改方法关闭弹框。
//子组件
<template>
<div>
<el-dialog title="提示" :visible.sync="dialogVisible" width="30%">
<span>这是一段信息</span>
<span slot="footer" class="dialog-footer">
<el-button @click="closeDialog">取 消</el-button>
</span>
</el-dialog>
</div>
</template>
<script>
export default {
props: {
dialogVisible: {
type: Boolean,
default: false
}
},
methods: {
closeDialog() {
this.$emit("update:dialogVisible", false); //这里使用$emit
}
},
}
</script>
//父组件
<template>
<div>
<h3>我是父组件</h3>
<el-button type="primary" @click="openDialog">点击打开弹窗</el-button>
<son :dialogVisible.sync="dialogVisible"></son> //这里用sync修饰绑定属性
</div>
</template>
<script>
import son from './son.vue'
export default {
data() {
return {
dialogVisible: false
}
},
components: {
son
},
methods: {
openDialog() {
this.dialogVisible = true
}
},
}
</script>
方法二
- 一般用于input框的值的绑定及改变
- 父组件里使用 v-model 给子组件绑定值
- 子组件里将props和computed里的set,get结合使用
//子组件
<template>
<div>
<div class="input-area">
<el-input v-model="inputVal"></el-input>
</div>
<el-button type="success" @click="changeValue">将输入框的值改为100</el-button>
</div>
</template>
<script>
export default {
props: {
value: {
type: [String, Number],
default: ""
}
},
methods: {
changeValue() {
this.inputVal = '100'
}
},
computed: {
inputVal: {
get() {
return this.value
},
set(newVal) {
this.$emit('input', newVal)
}
}
}
}
</script>
<style scoped>
.input-area {
width: 30%;
margin-bottom: 15px;
}
</style>
//父组件
<template>
<div>
<h4>我是父组件</h4>
<son v-model="comMyName"></son>
</div>
</template>
<script>
import son from './son.vue'
export default {
components:{
son
},
data() {
return {
comMyName:""
}
},
}
</script>
方法三
- 在子组件里,将props里面的值赋值给data里面的值
- 同时用watch监听props的变化,监听的时候赋值
- 用watch监听的必要性:vue里父组件变化,子组件不能及时更新,需要用watch监听props
<script>
props:{
item:{type:Object}
},
data(){
return {
data_item: this.item
}
},
watch:{
item(val){
this.data_item = this.item
}
}
</script>
方法四
直接改,好像现在可以改了,不确定是不是因为在父组件里绑值使用了v-model
<template>
<div class="box">
<h2>我是子组件</h2>
<el-input :value="value.input1" placeholder="请输入内容"></el-input>
<el-input v-model="value.input2" placeholder="请输入内容"></el-input>
<el-button @click="change">点击修改值</el-button>
</div>
</template>
<script>
export default {
props: {
value: {
type: Object,
},
},
methods: {
change() {
this.value.input1 = "cccc";
},
},
};
</script>
<template>
<div class="box">
<h2>我是父组件</h2>
<son v-model="value"></son>
</div>
</template>
<script>
import son from "./son.vue";
export default {
components: {
son,
},
data() {
return {
value: {
input1: "aaaa",
input2: "bbbb",
},
};
},
};
</script>