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>


分享到:


相關文章: