【问题标题】:Vue.js add component option (prop) using custom directiveVue.js 使用自定义指令添加组件选项(prop)
【发布时间】:2019-08-23 01:35:57
【问题描述】:

我有使用我自己的指令 (v-color) 的 Custom 组件:

<custom v-color="color" />

还有我的脚本,我定义了this.colorthis.changeColor()

{
   data () {
     return {
       color: red
     }
   },

   methods: {
     changeColor (color) {
       this.color = color
     }
   }
}

如何编写v-color指令的代码来更改&lt;custom /&gt;v-bind:color

换句话说,当组件加载时v-bind:color 的值将是red。如果this.color被方法修改(如this.changeColor('blue')),v-bind:color的值会自动更新。

我会感谢避免“观看”的解决方案,因为我会多次使用v-color

【问题讨论】:

  • v-color 是道具吗?如果是这样,颜色将是反应性的 &lt;custom :v-color="color" /&gt;
  • 这是一个指令。
  • 不应该 datedata
  • 谢谢,@DerekPollard。我编辑了我的问题。

标签: vue.js


【解决方案1】:

这样的东西似乎符合您的要求:

Vue.component('third-party-component', {
  props: ['color'],
  template: '<div :style="{ color }" v-cloak>{{color}}</div>'
});

Vue.component('hoc-component', {
  props: ['color'],
  computed: {
    transformedColor () {
      if (this.color === "blu") return "blue";
      if (this.color === "re") return "red";
      if (this.color == "or") return "orange";
      if (this.color == "pur") return "purple";
      return this.color;
    }
  },
  template: '<third-party-component  :color="transformedColor" />'
});

new Vue({
  el: '#app'
});
<html>
<body>
  <div id="app" v-cloak>
    <div>
      <hoc-component color="blu"></hoc-component>
      <hoc-component color="or"></hoc-component>
      <hoc-component color="re"></hoc-component>
      <hoc-component color="pur"></hoc-component>
      <hoc-component color="pink"></hoc-component>
      <hoc-component color="green"></hoc-component>
    </div>
  </div>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
</body>
</html>

这里我们利用高阶组件模式来修改我们需要的数据并将其传递给第三方组件。这是一种更有效的变异和处理数据更改的方法,而不会产生指令的副作用。

希望这会有所帮助!

【讨论】:

  • el.style.color 不是 v-bind:color
  • @CaioTarifa 所以你想将数据绑定到组件并且你不想使用内置的:color="color" ?
  • 是的,我需要使用指令而不是普通绑定来绑定color prop。
  • @CaioTarifa 介意说为什么?听起来您正在尝试使用诸如全局状态之类的东西来规避。也不知道你为什么不喜欢看
猜你喜欢
  • 1970-01-01
  • 2019-01-05
  • 2020-03-31
  • 2019-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-03
  • 2011-03-09
相关资源
最近更新 更多