export default { data () { return {msg: "header" } }}以上代码实际上会自动生成一个 new vue
export default{ data: function () {}, //data一定要是返回一个函数components: {comHeader: Header //声明组件 } }在template中使用
<template> <div class="com-app"><com-header></com-header> //注意,html不区分大小写,所以需要将 comHeader 写成 com-header</div></template>一个vue对象通常包括下面几个属性
data://vue对象的数据methods: //vue对象的方法watch: //对象监听的方法computed: //计算逻辑放到computed中created: //属性已绑定,dom未生成,一般在这里进行ajax处理以及页面初始化处理2. vuex
通过尤大大这张图,我们很清楚的看到,所有的数据流都是单向的,并且actions只能通过分发mutations来修改 store 实例的状态
像一些全局信息通用,比如 header内容的渲染,是否显示,loading 什么时候显示,什么时候隐藏,以及接口api的固定值,都写在store记录组件的state。
const store = new Vuex.Store({ state: { comm: {loading: false, //是否显示loadingapiUrl: "http://www.sherlochao.com:9091/photosharing/", //接口base urlimgUrl: "http://www.sherlochao.com:9091/filebase", //图片base urlindexConf: {isFooter: true, // 是否显示底部isSearch: true, // 是否显示搜索isBack: false, // 是否显示返回isShare: false, // 是否显示分享title: "" // 标题} } }})在mutations中改变state状态
const store = new Vuex.Store({mutations: { //loading的显示 isLoading: (state, status) => {state.comm.loading = status }, //修改header的信息 changeIndexConf: (state, data) => {Object.assign(state.comm.indexConf, data) }})e.g 在 header.vue 中 控制是否显示
export default { data: function () {return {} }, computed: {isShowSearch: function () {return this.$store.state.comm.indexConf.isSearch //获取vuex里面 state 状态值},title: function () {return this.$store.state.comm.indexConf.title},isBack: function () {return this.$store.state.comm.indexConf.isBack} }}template代码
<template> <div class="header"> <div v-show="isShowSearch"></div> <div class="title" v-show="!isShowSearch"><a v-show="isBack" class="back t-icon" @click="goBack"><spanclass="iconfont icon icon-xiangzuojiantou"></span></a><p>{{title}}</p> </div> </div></template>在其他地方控制 header 是否显示, e.g: 详情页面
export default {created: function () {vm.$store.commit("changeIndexConf", {isFooter: false,isSearch: false,isBack: true,isShare: true,title: "详情页"})} }3.开发实践总结
export default { watch: { "$route" (to, from) {// 对路由变化作出响应... } }}2.判断是否登陆
router.beforeEach(function (to,from,next) { var userMsg = localStorage.getItem("userMsg") if(to.path === "/home"){ if(!userMsg){next({ path: "/login" }) } } next()})3.常用api