1,Vuex:
state => 基本数据
getters => 从基本数据派生的数据
mutations => 提交更改数据的方法,同步!
actions => 像一个装饰器,包裹mutations,使之可以异步。
modules => 模块化Vuex
首先vuex是以插件的形式存在的,要引入import vuex from 'Vuex' ,Vue.use(Vuex)
要const 一个变量,并且注入vue的实例里面,store : 变量 (store和el,router同级)
let myvue = new Vue({
el:".container",
store:vuex_store, //注入到vue
router:routerConfig,
});
返回刚刚声明vuex的操作:
const vuex_store = new Vuex.store({
state:{
xxx:oooo; // 定义你的数据源
}
})
这里的state是默认值(固定),相当于一个全局的变量,当注入了vue实例时候,在其他组件写js的时候,
` export default{
methods:{
submit(){`
这种方式直接引用methods函数,同时调用this.store(实例里注册名字).commit(‘直接vuex里面的函数名xxx’,actions(Action 通过 store.dispatch 方法触发,所以之前写的是错误的)或者mutactions:{xxx():{}}) ,记住触发都是dispatch,commit,改变值的时候,用this.$store.state.xxx(state里面的名字)
export default{
data(){
return{
data里的一定是个函数,不像new vue 里的data,这是写死data的做法,(以下是组件的发送http请求的方法)
export default{
created(){
if (this.$store.state.newslist.length == 0){
// 请求服务器获取数据
this.$http.get("http://localhost/news.php").then(function (res) {
this.$store.state.newslist = res.body;
},function (res) {
// 请求失败处理
})
}
}
}
可能这个data不是数据绑定的,所以循环的时候v-for="news in this.$store.state.newslist"
当使用getter处理数据的时候
getters:{
getNews(state){
return state.newslist.filter(function (news) {
return !news.isdeleted;
})
}
}
循环的时候,由于是派生的数据
v-for="news in this.$store.getters.getNews"
基本的流程思路:在组件里面触发action的方法:
methods:{
submitAgree(){
// 组件了调用actions里定义的agree方法
this.$store.dispatch("agree",this.$store.state.newsdetail.id)
}
组件里面的actions方法Vue.http.post(‘url’,{json对象},{emulateJSON:true}).then(xx,yy),xx函数里面,更新state的值并且触发mutactions。(第一个参数都是state)。
2,vue-router。
一)定义路由组件。const Home = { template: '<div>首页</div>' }
二)定义组件,即组件包含的路径及其路由组件
const routes = [
{ path: '/home', component: Home },
{ path: '/news', component: News }
]
三)创建router实例
const router = new VueRouter({
routes // (缩写)相当于 routes: routes
})
四)传入到实例里面
const app = new Vue({
router
}).$mount('#box')
其他:{ path: '/', redirect: '/home' },
路由的重定向默认到path为home下面去
嵌套路由:在定义路由的的时候加个children属性:
{ path: '/', redirect: '/home' },
{
path: '/home',
component: Home,
children:[
{ path: '/home/login', component: Login},
{ path: '/home/reg', component: Reg}
]
},
{ path: '/news', component: News}
定义传参路由:{ path: '/news/:id', component: NewsDetail },
路由组件<span>{{$route.params.id}}</span>
获取参数
补充:在vue2.0里面已经不用vue.http.post 或者this.$http.get 的方法请求,而是用axios
可以在组件里面写methods或者vuex的actions里面封装
Vue.prototype.$ajax = axios
methods :{
submitForm () {
this.$ajax({
method: 'post',
url: '/user',
data: {
name: 'wise',
info: 'wrong'
}
})
}
actions: {
// 封装一个 ajax 方法
saveForm (context) {
axios({
method: 'post',
url: '/user',
data: context.state.test02
})
}
}
})
学习传送门:vuex
vue-router
搭建
总结
引用:mutation 只管存,你给我(dispatch)我就存;action只管中间处理,处理完我就给你,你怎么存我不管;Getter 我只管取,我不改的。 action放在了 methods 里面,说明我们应该把它当成函数来用(讲道理,钩子函数也应该可以的) mutation是写在store里面的,这说明,它就是个半成品,中间量,我们不应该在外面去操作它。getter写在了 computed 里面,这说明虽然 getter我们写的是函数,但是我们应该把它当成计算属性来用。
未完待续…^_-