在作用域插槽内使用 v-model
[英] Using v-model inside scoped slots
本文介绍了在作用域插槽内使用 v-model的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用 Vue 2.6.9 和新的 v-slot 语法.我想访问与插槽内的 v-model 交互.问题是在槽内显示数据有效,但使用 v-model 不行.这是我的代码:
Vue.component('base-test', {模板:`<div><slot :foo="foo" :foo2="foo2"></slot>
`,数据(){返回{foo: '酒吧',foo2: '酒吧 2'}}});//山新的 Vue({el: '#app'});<div id="应用程序"><base-test v-slot="sp"><div>foo2 是 {{ sp.foo2 }}</div><input type="text" v-model="sp.foo"><div>foo 是 {{ sp.foo }}</div></base-test>
Codepen
我的问题是如何从插槽内与组件数据进行交互.
解决方案
关于 this 问题,Vue 核心成员说你不应该修改你传递给插槽的数据.
您应该传递一个方法来更改值.如果您同意这一点,请遵循 this 答案.
但是,有一种利用 Javascript 参考值的棘手方法
不是传递原始值(不会具有反应性),而是传递一个反应性对象,该对象将保持其反应性(例如 Observer、reactiveGetter、reactiveSetter).
子组件
<div class="child"><slot :model=model"></slot>
</模板><脚本>导出默认{数据:() =>({模型: {值:初始值",},}),};
父组件
<div id="应用程序"><子v-slot={模型}"><输入类型=文本"v-model=model.value"/></孩子>
</模板><脚本>从./components/Child"导入孩子;导出默认{成分: {孩子,},};
在codesandbox上实时查看.
I'm using Vue 2.6.9 with the new v-slot syntax. I want to access interact with v-model inside slot. The problem is that showing data inside slot works, but using v-model does not. Here is my code:
Vue.component('base-test', {
template: `
<div>
<slot :foo="foo" :foo2="foo2"></slot>
</div>
`,
data(){
return{
foo: 'Bar',
foo2: 'Bar 2'
}
}
});
// Mount
new Vue({
el: '#app'
});
<div id="app">
<base-test v-slot="sp">
<div>foo2 is {{ sp.foo2 }}</div>
<input type="text" v-model="sp.foo">
<div>foo is {{ sp.foo }}</div>
</base-test>
</div>
Codepen
My question is how to interact with the component data from within slot.
解决方案
Regarding this issue, Vue core member says that you should not modify the data you pass to a slot.
You should pass a method to change the value. If you agree with this, then follow this answer.
However, there is a tricky way to do it by taking advantage of Javascript reference values
Instead of passing a primitive value (which will not have reactivity), you pass a reactive object which will keeps its reactivity (eg Observer, reactiveGetter, reactiveSetter).
Child component
<template>
<div class="child">
<slot :model="model"></slot>
</div>
</template>
<script>
export default {
data: () => ({
model: {
value: "Initial value",
},
}),
};
</script>
Parent component
<template>
<div id="app">
<Child v-slot="{ model }">
<input type="text" v-model="model.value" />
</Child>
</div>
</template>
<script>
import Child from "./components/Child";
export default {
components: {
Child,
},
};
</script>
See it live on codesandbox.
这篇关于在作用域插槽内使用 v-model的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!