【问题标题】:How to get state item via props in vuejs with vuex如何使用 vuex 通过 vuejs 中的道具获取状态项
【发布时间】:2018-11-04 20:54:43
【问题描述】:

对不起,我的英语不好。 我已经从 vue 中选择了道具。我想通过 props 值获取状态选择项。

我来自组件。

<template>
    <h1>this.$store.state.fromSelected</h1>
</template>
<script>
    export default {
       props: ['fromSelected']
    }
</script>

像这样处于vuex状态

const state = {
   'one': null,
}

我像这样在根组件中使用我的 from 组件

<from from-selected="one"></from>

当我使用 this.$store.state.fromSelected 时,我想从组件中获取 this.$store.state.one

【问题讨论】:

标签: vue.js state vuex


【解决方案1】:

看来您面临的问题与 Vue 和 Vuex 中的数据流有关。这里需要解决两个不同的问题:

问题编号。 1 - 数据流和范围:

在您的模板代码中:&lt;h1&gt;this.$store.state.fromSelected&lt;/h1&gt; 您正在尝试访问处于 Vuex 状态的组件属性。它不会在那里存在,因为它只存在于组件本地范围内。以下是数据流如何工作的说明:

问题编号。 2 - 静态和动态道具:

&lt;from from-selected="one"&gt;&lt;/from&gt; 行中,您没有在属性前面加上冒号,因此道具将被视为字符串文字,而不是您可以传入变量的表达式。在这里阅读更多:https://vuejs.org/v2/guide/components-props.html#Static-and-Dynamic-Props

解决办法:

解决方案是将 Vuex 状态的值作为动态属性传递给组件;像这样:

// Javascript
const store = new Vuex.Store({
  state: {
    one: "This comes from the Vuex state"
  },
})

new Vue({
  el: "#app",
  store: store,
  components: {
    from: {
      template: '<span>{{ fromSelected }}</span>',
      props: ['fromSelected']
    }
  }
})

// Template
<div id="app">
  <from :from-selected="$store.state.one"></from>
</div>

在这里试试:https://jsfiddle.net/vngrcu5v/

【讨论】:

    【解决方案2】:

    我发现了。我必须这样写。

    // From.vue component
    <template>
       <span>{{this.fromSelected}}</span>
    
    
     </template>
        <script>
           export default {
                props: ['fromSelected']
           }
        </script>
    
    
    
    // Root component
        import from from 'from';
    
        <from :from-selected="this.$store.state.one"></from>
    
    
    
    // State 
    export default {
       'one': null,
    }
    

    【讨论】:

    • 这是基于我的小提琴jsfiddle.net/vngrcu5v 吗?如果是这样,您是否希望我清理答案,以便其他人发现这个问题更容易理解?
    • 是的。你的代码很完美。我只是使用你的代码。谢谢大家
    • 不用担心。我现在已经做出了更完整的答案来解决所有问题。如果正确,请采纳我的回答。
    【解决方案3】:

    您是否尝试使用相同的语法放置 fromSelected

    <from fromSelected="one"></from>
    

    【讨论】:

    • 在 Vue.js 中,您可以在定义控制器时将 props 指定为 camelCase,并在 HTML 中使用组件 props 时使用连字符大小写。
    • 啊,好吧,我从不使用camelCase .. thk
    猜你喜欢
    • 2017-08-17
    • 2018-04-14
    • 1970-01-01
    • 1970-01-01
    • 2021-03-28
    • 2018-12-21
    • 1970-01-01
    • 2017-10-30
    • 2020-11-13
    相关资源
    最近更新 更多