【https://stackoverflow.com/】beforeCreate钩子中出错:“TypeError:无法设置#的属性$store,该属性只有getter laravel

Vuex: [Vue warn]: Computed property “username” was assigned to but it has no setter

我尝试从全局vuex状态设置并获取用户名、密码和身份验证布尔值,并有条件地在导航栏中呈现某些元素。下面是应该传递数据的登录组件:

<template>
  <div class="login" id="login">
    <b-form-input
      id="inputfield"
      v-model="username"
      type="text"
      placeholder="username">
    </b-form-input>
    <b-form-input
      id="inputfield"
      type="password"
      v-model="password"
      placeholder="password">
    </b-form-input>
    <b-button @click="login()" id = "inputfield" variant="outline-success">
      Login
    </b-button>
  </div>
</template>

<script>
  export default {
    name:  login ,
    computed: {
      username () {
        return this.$store.state.username
      },
      password () {
        return this.$store.state.password
      },
      loggedIn () {
        return this.$store.state.loggedIn
      }
    },
    methods: {
      login () {
        this.$store.dispatch( login , {
          username: this.username,
          password: this.password,
          isAuthed: true // just to test
        })
      }
    }
  }
</script>

不过,当我在输入字段中输入任何内容时,Vue会对该字段发出警告(状态不会更新):

[Vue warn]: Computed property "username" was assigned to but it has no setter.

1答案

您使用的是带有计算属性的v-model,因此实际上您正在尝试在输入事件激发时更新该计算属性。
因此,需要为计算属性设置setter。
当您尝试使用Vuex状态时,计算属性的设置器可以向store提交mutations。

computed: {

  username : {
    get () {
      return this.$store.state.username
    },
    set (value) {
      this.$store.commit( updateUsername , value)
    }
  },

  password : {
    get () {
      return this.$store.state.password
    },
    set (value) {
      this.$store.commit( updatePassword , value)
    }
  },

  ...

},

你需要为你的store设置相应的mutations,例如:

mutations: {

  updateUsername (state, username) {
    state.username = username
  },

  updatePassword (state, password) {
    state.username = password
  },

  ...

}

有关详细信息,请参阅Vuex文档中的说明:https://vuex.vuejs.org/en/forms.html


对于登录按钮,您正在尝试分派一个操作。如果您只想在存储中设置一个布尔值,那么可以这样调度操作:

methods: {
  login () {
    this.$store.dispatch( login , true)
  }
}

…然后在您的store中,您将需要相应的action 和mutation来commit:

mutations: {
  login (state, value) {
    state.isAuthed = value
  }
},

actions: {
  login ({ commit }) {
    commit( login )
  }
}

以下是操作文档:https://vuex.vuejs.org/en/actions.html
I hope this helps.
来源:https://stackoverflow.com/questions/47460765/vuex-vue-warn-computed-property-username-was-assigned-to-but-it-has-no-set

© 版权声明
THE END
如果内容对您有所帮助,就支持一下吧!
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容