【问题标题】:How to change the value of a prop (or data) of a component, from OUTSIDE the component?如何从组件外部更改组件的道具(或数据)的值?
【发布时间】:2018-02-18 03:47:49
【问题描述】:

正如标题所说,我正在尝试更改组件中 prop/data 的值,但触发器是从组件外部触发的,与 Vuejs 无关。

目前我尝试使用简单状态管理器,基于来自here 的文档,如下所示:

var store = {
  debug: true,
  state: {
    progress: 23
  },
  setProgress (uff) {
    if (this.debug) console.log(uff)
    this.state.progress = uff
  }
}

文档让我相信,如果 progress 的值发生突变,如果我相应地链接它们,我的 Vue 实例的值也会发生变化。但这在组件中不起作用(我的猜测是因为它是一个函数)。

这是我的组件的一部分:

Vue.component('transcoding', {
  data () {
    return {
      progress: store.state.progress
    }
  },
  template: `
    <v-progress-circular
        :size="130"
        :width="25"
        :value="progress"
        color="teal"
      >
      {{progress}}
    </v-progress-circular>
  `
})

所以,当我触发store.setProgress(value) 时,什么也没有发生。日志消息确实发生了,但组件中的状态没有更新。

这是当前触发状态更改的脚本:

App.cable.subscriptions.create(
  { channel: "ProgressChannel", room: "2" },
  { received: function() {
    store.setProgress(arguments[0])
   }}
)

它是 Ruby on Rails 中的 ActionCable websocket。触发器完美运行,但我无法在状态更改和组件之间建立联系。

我尝试在组件的mounted() 事件中加载此脚本,认为我可以像这样引用该值:

Vue.component('transcoding', {
  data () {
    return {
      progress: 0
    }
  },
  template: `
    <v-progress-circular
        :size="130"
        :width="25"
        :value="progress"
        color="teal"
      >
      {{progress}}
    </v-progress-circular>
  `,
  methods: {
    setProgress: function(uff) {
      this.progress = uff
    }
  },
  mounted() {
    App.cable.subscriptions.create(
      { channel: "ProgressChannel", room: "2" },
      { received: function() {
        this.setProgress(arguments[0])
       }}
    )
  }
})

但这给了我一个错误,说 this.setProgress 不是一个函数,这很明显,因为我在 App.cable.subscriptions 的 create 方法中调用它。

我怎样才能做到这一点?我意识到我将问题与我的问题混为一谈,但我想说明我的目标是什么。我只是想知道如何让组件的progress 数据更新,无论是从外部还是从组件本身,如果我可以让它找到功能。

【问题讨论】:

  • 它的 $store 不是存储。 Vue 的所有内置属性都使用“$”符号访问/声明
  • 嗯……呃。让我测试一下。

标签: vue.js actioncable


【解决方案1】:

您正在初始化您的数据项到存储中的值:

  data () {
    return {
      progress: store.state.progress
    }
  }

对存储的更改不会传播到您的数据项。您可以删除数据项并在需要的地方使用store.state.progress,或者如果您想要一个本地单名句柄,您可以创建一个返回其值的computed。

【讨论】:

    猜你喜欢
    • 2019-03-13
    • 2019-07-26
    • 1970-01-01
    • 2018-12-07
    • 1970-01-01
    • 2021-10-20
    • 1970-01-01
    • 2019-09-15
    • 1970-01-01
    相关资源
    最近更新 更多