cbl*_*bll 2 vue.js vuex vuejs2
我试图从全局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>
Run Code Online (Sandbox Code Playgroud)
但是,当我在输入字段中输入任何内容时,Vue会为该字段发出警告(并且状态不会更新):
[Vue warn]: Computed property "username" was assigned to but it has no setter.
Run Code Online (Sandbox Code Playgroud)
Ste*_*ado 12
您正在使用具有计算属性的v-model,因此您实际上在输入事件触发时尝试更新该计算属性.
因此,您需要为计算属性设置setter.
当您尝试使用Vuex状态时,您的计算属性的setter可以将变量提交给商店.
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)
}
},
...
},
Run Code Online (Sandbox Code Playgroud)
您需要为商店提供相应的变异,例如:
mutations: {
updateUsername (state, username) {
state.username = username
},
updatePassword (state, password) {
state.username = password
},
...
}
Run Code Online (Sandbox Code Playgroud)
有关更多详细信息,请参阅此处Vuex文档中的说明:https://vuex.vuejs.org/en/forms.html
对于您的登录按钮,您正在尝试发送操作.如果您只想在商店中设置一个布尔值,那么您可以像这样调度操作:
methods: {
login () {
this.$store.dispatch('login', true)
}
}
Run Code Online (Sandbox Code Playgroud)
...然后在您的商店中,您将需要相应的操作和变异来提交:
mutations: {
login (state, value) {
state.isAuthed = value
}
},
actions: {
login ({ commit }) {
commit('login')
}
}
Run Code Online (Sandbox Code Playgroud)
以下是操作文档:https: //vuex.vuejs.org/en/actions.html
我希望这有帮助.
| 归档时间: |
|
| 查看次数: |
7034 次 |
| 最近记录: |