代码改变世界

vue学习小结1

2017-09-14 10:47  好像在哪见过你  阅读(206)  评论(0编辑  收藏  举报

在学vue之前要了解为什么学vue?与angular或者react相比,它有哪些优势?,这三个框架都是MVVM模式的,相对于angular的高学习成本,react虚拟节点的难以控制,我选择了轻量级的,代码看起来优雅的Vue框架。

下面总结下开发中碰到的问题。

1. 使用computed获取vuex公共变量

在使用vuex对状态进行管理的时候,在获取state上的值时,请在computed选项中声明获取,否则变量的同步会出现问题。

2.数组更新问题

因为Vue使用的是defineProperty的方式进行监测变化,因此Vue无法监测到数组以下的变动

(1)当你利用索引直接设置一个项时,如:vm.items[indexOfItem] = newValue

(2)当你修改数组的长度时,如:vm.items.length = newLength

以上的问题应该按如下的方式触发

Vue.set(example1.items,indexOfItem,newValue)

example1.items.splice(indexOfItem,1,newValue)

example1.items.splice(newLength)

 

3. 组件

3.1组件命名

HTML特性是不区分大小写的,所以当使用的不是字符串模版,驼峰命名的prop需要转换为对应的短横线隔开的方式命名:

Vue.component('child', {

  props: ['myMessage'],

  template: '<span>{{myMessage}}</span>'

})

<child my-message="hello world"></child>

 

3.2 Vue使用的是单向数据流,提倡props down,event up方式,通过使用Props传递数据,子组件通过$emit自定义方式,去唤醒父组件变更数据:

this.$emit('say', message)

<child @say="toSay" message="Hello!"></child>

 

通过@say对其自定义事件进行侦听,事件触发后,执行父组件的toSay()去驱动更新数据

methods: {

  toSay() {this.message = otherVal;}

}

 

3.3点击子组件触发方法

如你使用了vue-router,并希望在<router-link></router-link>被点击的时候,调用当前的方法

<router-link v-on:click.native="dosomething"></router-link>

 

4 路由

进入信息页面,由于需要判断是否已登录,此时由router进行一个拦截,具体代码如下:

router.beforeEach(function(to,from,next){
  var userMsg = localStorage.get('userImg');
  if(to.path === '/home'){
    if(!userMsg){next({path: '/login'})}
  }
  next();
})

 

路由跳转

路由设置如下:

{
path:'/tab',
component:Tab,
children:[{
path:'layoutList',
name:'LayoutList',
component:LayoutList
},{
path:'layoutView/:layoutId',
name:'LayoutView',
component:LayoutView
},{
path:'layoutDetail/:viewId',
name:'LayoutDetail',
component:LayoutDetail
}]
}

 

其中/tab是根地址,有3个子地址,3个子地址层级为:LayoutList => LayoutView => LayoutDetail

正常情况:假设当前路由为/tab/layoutList,需要跳转到LayoutView页面,可以通过router.push({path:'layoutView/'+item.id})

跳转后的路由为/tab/layoutView/1

跳转前地址:/tab/layoutView/1

跳转代码:router.push({path:'/tab/layoutDetail/'+item.id});

跳转后地址:/tab/layoutDetail/27

只有按照情况四的操作,才能正常显示出来页面。

vue路由会根据push的地址,如果地址不是/开头,会直接替换当前路由的最后一个/后的地址,

如果地址是/开头,会以push的地址作为绝对地址进行跳转。

另外我尝试还使用router.go({name:'LayoutDetail',params:{viewId:item.id}}),页面不会跳转且地址也不会改变。