Vuex入门实例教程

Vuex入门实例教程

本案例为Vuex简单的入门使用教程,目的是对vuex在vue中的使用有一个初步的认识。

Vuex的使用基本分为三步:
1、定义store。

在vue项目src目录下新建store/store.js,在文件中定义好store:

<code>

import

Vue

from

'vue'

;

import

Vuex

from

'vuex'

;Vue.use(Vuex);const store =

new

Vuex.Store({ state: { count:

0

, show:

''

, }, getters: { counts:

(state)

=>

{

return

state.count; } }, mutations: { increment:

(state)

=>

{ state.count++; }, decrement:

(state)

=>

{ state.count--; }, changeTxt:

(state, v)

=>

{ state.show = v; } } });

export

default

store;/<code>

2、引入store。

在main.js里面引入store.js

<code>

import

Vue

from

'vue'

import

App

from

'./App.vue'

import

Element

from

'element-ui'

import

'element-ui/lib/theme-chalk/index.css'

import

store

from

'./store/store'

Vue.config.productionTip =

false

;Vue.use(Element);

new

Vue({ store,

render

:

h

=>

h(App),}).$mount(

'#app'

)/<code>

3、使用store。

在组件demo.vue中使用store。

<code>

<

template

>

<

div

class

=

"store"

>

<

p

>

{{$store.state.count}}

p

>

<

el-button

@

click

=

"handleIncrement"

>

<

strong

>

+

strong

>

el-button

>

<

el-button

@

click

=

"handleDecrement"

>

<

strong

>

-

strong

>

el-button

>

<

hr

>

<

h3

>

{{$store.state.show}}

h3

>

<

el-input

aria-placeholder

=

"请输入内容"

v-model

=

"obj"

@

change

=

"changeObj"

clearable

>

el-input

>

div

>

template

>

<

script

>

export

default

{

name

:

"Demo"

, data() {

return

{

obj

:

''

} },

methods

: { handleIncrement() {

this

.$store.commit(

'increment'

); }, handleDecrement() {

this

.$store.commit(

'decrement'

); }, changeObj() {

this

.$store.commit(

'changeTxt'

,

this

.obj); } } }

script

>

<

style

scoped

>

style

>

/<code>


分享到:


相關文章: