-
监听数据变化
watch
data() { return { cart: JSON.parse(localStorage.getItem("cart")) || [] } }, watch: { cart(n) { localStorage.setItem("cart", JSON.stringify(n)) } } // 深度监听 watch: { cart: { handler(n) { localStorage.setItem("cart", JSON.stringify(n)) }, deep: true } }
-
vue-router
- 安装:
vue add router
- 路由配置
Vue.use(VueRouter) const routes = [ { path: '/', component: App, children: [ { path: '', name: 'index', component: index }, { path: 'product/:id', name: 'product', // 在对应组件内,props: ['id'] 即可直接使用,避免路由耦合 props: true, // 路由独享 beforeEnter: (to, from, next) => { if (XXX) { next('/login') } else { next() } }, component: detail }, { path: '**', name: 'index', component: index } ] } ] // 路由实例 const router = new VueRouter({ routes, mode: 'history', strict: true, scrollBehavior (to, from, savedPosition) { if (savedPosition) { return savedPosition } else { if (from.meta.keepAlive) { from.meta.savedPosition = document.body.scrollTop; } return { x: 0, y: to.meta.savedPosition ||0 } } } }) // 每次路由激活之前都会执行回调函数 router.beforeEach((to, from, next) => { // 判断是否登录 if (to.path.includes('detail') && XXX) { next('/login') } else { next() } }) export default router
- 路由守卫
- 全局
beforeEach(to,from,next)
- 路由独享
beforeEnter(to,from,next)
- 组件
beforeRouteEnter(to,from,next)
- 全局
- 安装:
-
vuex
- 安装
vue add vuex
- 状态与变更
export default new Vuex.Store({ state: { count:0 }, mutations: { add(state) { state.count++ } } })
- 派生状态
export default new Vuex.Store({ getters: { todoCount(state) { return state.todos.filter(todo=>!todo.completed).length } } })
- 异步操作
export default new Vuex.Store({ actions: { // do something someAction(context) { // 访问状态 context.state; // 提交变更 context.commit(); // 派发动作 context.dispatch(); } } })
- 简化方法
export default { computed: { ...mapState(['isLogin']), ...mapGetters(['loginState']) }, methods: { ...mapActions(['login']) } }
- 安装
网友评论