vue.js - vuejs - 计算不适用于 Prop

标签 vue.js

我正在使用 Prop 来更新子组件中的网站内容。这基本上是这样工作的:

<child-component :updatedArray="updatedArray" />
然后在子组件中:
<template>
   {{updatedArray}}
   <div>{{computedArray}}</div>
</template>
<script>
   props: ['updatedArray'],
   ...
   computed: {
      computedArray() {
        if(this.updatedArray.item == "item one") {return "item one"}
       else {return "other item"}
       }
   }
</script>
现在,当我更新 updatedArray 时,这段代码在任何情况下都应该可以工作。在我的父组件中。然后我在我的子组件中看到我的 {{updatedArray}}更改正确,但我的 computedArray未触发且不起作用。
我能问你为什么会这样吗?
计算是否不适用于每个 Prop 更新?
我应该如何更正我的代码?
编辑:不重复
我没有改变 Prop ,我宁愿只根据它的值进行计算。

最佳答案

您的绑定(bind)使用了错误的名称。

Vue Guide描述:

HTML attribute names are case-insensitive, so browsers will interpret any uppercase characters as lowercase. That means when you’re using in-DOM templates, camelCased prop names need to use their kebab-cased (hyphen-delimited) equivalents



所以你需要转换 Camel 箱烤肉串 .

喜欢 v-bind:updated-array而不是 v-bind:updatedArray .

下面是一个使用 kebab-case 的工作演示。您可以将其更改为camelCase,然后您会发现不起作用。

Vue.component('child', {

  template: '<div><span style="background-color:green">{{ updatedArray }}</span><div style="background-color:red">{{computedArray}}</div></div>',
  props: ['updatedArray'],
  computed: {
    computedArray() {
      if(this.updatedArray.item.length > 0) {return this.updatedArray}
      else {return "other item"}
    }
  }
})

new Vue({
  el: '#app',
  data() {
    return {testArray: {
      'item': 'test',
      'prop1': 'a'
    }}
  },
  methods:{
    resetArray: function() {
      this.testArray['item'] += this.testArray['prop1'] + 'b'
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="app">
<button v-on:click="resetArray()">Click me</button>
<child v-bind:updated-array="testArray"></child>
</div>

关于vue.js - vuejs - 计算不适用于 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49614574/

相关文章:

vue.js - Vue 和 Webpack 中的动态导入路径

vue.js - d3-sankey 链接在拖动事件时未更新

javascript - 方法在单元测试中不可用

javascript - 如何使用 Tailwind 和 Vue.js 动态显示移动菜单?

javascript - Vue 和 Laravel 表单验证未返回 422 响应

vue.js - 如何在 vue.js 2 的输入类型文本中添加运算符三元?

javascript - 用Vue调用同一个组件的方法

vuejs2 - 在文本框 VueJS 2 中键入时搜索列表

vue.js - Vue v-model 对 BS4 单选按钮组没有反应

vue.js - v-for,如何打开点击的列表项