gpt4 book ai didi

javascript - Vue Scoped Slots 组件和插槽之间的双向数据绑定(bind)

转载 作者:行者123 更新时间:2023-12-02 21:28:35 25 4
gpt4 key购买 nike

我有一个作用域插槽。我需要传递到插槽的内容才能影响父模板。

这是我到目前为止所拥有的:

Parent.vue

<template>
<div>
<slot :text="text" :msg="msg"/>
<p>{{text}}</p>
<p>{{msg}}</p>
</div>
</template>

<script>
export default {
name: "Parent",
data() {
return {
text: "",
msg: ""
};
}
};
</script>

应用程序.vue

<template>
<parent>
<template #default="{ text, msg }">
<input type="text" v-model="text"/>
<input type="text" v-model="msg"/>
</template>
</parent>
</template>

<script>
import Parent from "./components/Parent";

export default {
name: "App",
components: {
Toolbar
},
}

这行不通。我怎样才能做类似的事情?

最佳答案

这是不可能的。您无法更改提供给组件(App.vue)的 Prop (在本例中为插槽 Prop ),但您可以使用“处理程序”方法执行类似的操作。

Parent.vue

<template>
<div>
<slot :text="text" :msg="msg" :setValue="setValue" />
<p>{{ text }}</p>
<p>{{ msg }}</p>
</div>
</template>

<script>
export default {
name: 'Parent',
data() {
return {
text: '',
msg: ''
};
},
methods: {
// set the current value with a function
setValue(e) {
this[e.target.name] = e.target.value;
}
}
};
</script>

App.vue

<template>
<parent>
<template #default="{ text, msg, setValue }">
Text: {{ text }}<br />
Msg: {{ msg }}<br /><br />
<!-- I have named the input fields after the variables in your data object and have the "setValue" method triggered by @input. -->
<input type="text" name="text" @input="setValue" />
<input type="text" name="msg" @input="setValue" />
</template>
</parent>
</template>

<script>
import Parent from './components/Parent';

export default {
name: 'App',
components: {
Parent
}
};
</script>

关于javascript - Vue Scoped Slots 组件和插槽之间的双向数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60676730/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com