vue,vue-router,vux,综合

实例化vue实例时初始化router store 状态管理。触发router去渲染对应的组件,然后通过对组件组件的操作来完成状态的变更。
先引入js脚本
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<script src="https://unpkg.com/vuex@2.1.1"></script>

html
<div id="app">
<router-view ></router-view>
</div>


js脚本

const Foo = {
template: '<div v-on:click="increase">foo{{count1}}</div>',
// 该组件的私有数据
data:function(){
return {count:10};
},
computed:{
done:function(){
return this.$store.getters.doneTodos;
},
count1:function(){
return this.$store.state.count;
}
},
methods:{
increase:function(){
this.$store.commit("increase",4);
}
}
}
const Bar = {
// 该组件的view
template: '<div v-on:click="decrease">bar{{count}}</div>',
// 该组件的方法
methods:{
decrease:function(){
this.$store.commit("decrease");
}
},
// 该组件的计算属性
computed:{
count:function(){
return this.$store.state.count;
}
}
};
const Baz = { template: '<div>baz</div>'}
// Vue.component('topic', {
// template:"<span>这是topic</span>"
// })
// 实例化路由
const router = new VueRouter({
mode: 'history',
routes: [
{ path: '/bar',
name:"bar",
component: Bar
},
{ path: '/foo',
name:"foo",
component: Foo
},
{
path: '/other',
components: {
default: Baz,
a: Bar,
b: Foo
}
}
]
})
// 初始化store实例
var store=new Vuex.Store({
// 声明需要使用到的共享状态
state:{
todos:[
{id:1,done:true},
{id:2,done:false},
{id:3,done:true}
],
count:0
},
// 可以理解为计算属性
getters:{
doneTodos:function(state){
return state.todos.filter(function(todo){
return todo.done;
})
}
},
// 定义事件
// 组件内部统一通过 this.$store.commit("increase",obj)来进行提交更改需求
mutations:{
increase(state,a,b){
console.log(state,a,b)
state.count++;
},
decrease:function(state){
console.log("count:"+state.count);
state.count--;
console.log("count:"+state.count);
}
}
})
window.a=new Vue({
router:router,//绑定路由,传入router实例到vue 组件内部可以通过this.$router来访问路由对象
store:store//将实例化后的store绑定到根节点,则任意组件都可以通过this.$store来访问到store实例
}).$mount("#app");


测试:a.$router.push({name:'bar'})
a.$router.push({name:'foo'})

然后可以进行点击,发现在foo组件下点击后store.count变为1,
切换路由到bar下面后,count也是1.这样便实现了有效管理。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值