首先是头部和和尾部
先引入vuex和vue-router
window.Vue = require('vue')
import VueRouter from 'vue-router'
import Vuex from 'vuex'
Vue.use(VueRouter)
Vue.use(Vuex)
在components文件夹下建立Header.vue和Footer.vue,并加入前端html
然后在application.jszh中全局注册组件
Vue.component('header-box', require('../components/Header.vue'))
Vue.component('footer-box', require('../components/Footer.vue'))
接下来我们需要获取数据,并存入store中
vuex有几个东西: state, getter, mutations, actions,具体的我也没理解清楚,可参考文档和以下lian链接
https://appdividend.com/2018/05/08/vuex-axios-get-request-tutorial-with-example/
const state = {
categories: '',
productTree: '',
config: ''
}
const mutations = {
SET_CATEGORIES(state, categories){
state.categories = categories
},
SET_CONFIG(state, config){
state.config = config
},
SET_PRODUCT_TREE(state, productTree){
state.productTree = productTree
}
}
const actions = {
loadInit ({ commit }) {
axios.get('/api/initweb')
.then(r => r.data)
.then(coins => {
commit('SET_CONFIG', coins.data.config)
commit('SET_CATEGORIES', coins.data.categories)
commit('SET_PRODUCT_TREE', coins.data.product_tree)
})
}
}
const store = new Vuex.Store({
state: state,
mutations: mutations,
actions: actions
})
coins.data的使用是因为我后端数据都存入data中的
然后把store加入vue中
new Vue({
router,
store
}).$mount('#app')
接下来就是在组件中使用数据了
以之间建立的Header.vue为例
先获取数据:
mounted () {
this.$store.dispatch('loadInit')
},
在把数据渲染到页面:
computed: {
...mapState([
'categories',
'config'
]),
}
需要引入
import { mapState } from 'vuex'
<template>
<div class="header">
<div class="container">
<div class="row header-bar">
<div class="col-3 logo"><img src="/images/logo-200.png" /></div>
<div class="col-9 text-right phone"><i class="fa fa-volume-control-phone"></i> {{ config.phone }}</div>
<div class="col-9 text-right menu"><i class="fa fa-align-justify"></i></div>
</div>
<nav class="header-nav">
<ul>
<li>
<a href="">首页</a>
</li>
<li v-for="category in categories" :key="category.id">
<router-link :to="{path: '/' + category.module + '/' + category.id}">{{category.title}}</router-link>
</li>
</ul>
</nav>
</div>
</div>
</template>
<script>
import { mapState } from 'vuex'
export default {
mounted () {
this.$store.dispatch('loadInit')
},
computed: {
...mapState([
'categories',
'config'
]),
}
}
</script>
这里的template只能包含一个大标签
Footer.vue也是一样