首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Vue作用域插槽组件和插槽之间的双向数据绑定

Vue作用域插槽组件和插槽之间的双向数据绑定
EN

Stack Overflow用户
提问于 2020-03-13 20:12:18
回答 1查看 3.2K关注 0票数 1

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

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

Parent.vue

代码语言:javascript
复制
<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>

App.vue

代码语言:javascript
复制
<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
  },
}

这不管用。我怎样才能做这种事呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-03-13 20:45:21

这是不可能的您不能更改提供给组件(App.vue)的道具(在本例中是插槽道具),但是您可以使用“处理程序”方法这样做。

Parent.vue

代码语言:javascript
复制
<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

代码语言:javascript
复制
<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>
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60676730

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档