VUE简单的语法

这篇主要记录了在使用过程的当中,对于vue的一些方法的理解

1.Vue生命周期中mounted和created的区别

created:在模板渲染成html前调用,即通常初始化某些属性值,然后再渲染成视图。
mounted:在模板渲染成html后调用,通常是初始化页面完成后,再对html的dom节点进行一些需要的操作。
其实两者比较好理解,通常created使用的次数多,而mounted通常是在一些插件的使用或者组件的使用中进行操作,比如插件chart.js的使用: var ctx = document.getElementById(ID);通常会有这一步,而如果你写入组件中,你会发现在created中无法对chart进行一些初始化配置,一定要等这个html渲染完后才可以进行,那么mounted就是不二之选。下面看一个例子(用组件)。

例子

[javascript] view plain copy
 
  1. <span style="font-size:14px;">Vue.component("demo1",{  
  2.         data:function(){  
  3.             return {  
  4.                 name:"",  
  5.                 age:"",  
  6.                 city:""  
  7.             }  
  8.         },  
  9.         template:"<ul><li id='name'>{{name}}</li><li>{{age}}</li><li>{{city}}</li></ul>",  
  10.         created:function(){  
  11.             this.name="唐浩益"  
  12.             this.age = "12"  
  13.             this.city ="杭州"  
  14.             var x = document.getElementById("name")//第一个命令台错误  
  15.             console.log(x.innerHTML);  
  16.         },  
  17.         mounted:function(){  
  18.             var x = document.getElementById("name")/</span>/第二个命令台输出的结果<span style="font-size:14px;">  
  19.             console.log(x.innerHTML);  
  20.         }  
  21.     });  
  22.     var vm = new Vue({  
  23.         el:"#example1"  
  24.     })</span>  
可以看到输出如下:
可以看到都在created赋予初始值的情况下成功渲染出来了。
但是同时看console台如下:
可以看到第一个报了错,实际是因为找不到id,getElementById(ID) 并没有找到元素,原因如下:
在created的时候,视图中的html并没有渲染出来,所以此时如果直接去操作html的dom节点,一定找不到相关的元素
而在mounted中,由于此时html已经渲染出来了,所以可以直接操作dom节点,故输出了结果“唐浩益”。
 
 
 
二 、异步加载之后的回调函数的使用

最近,在项目中要使用Swiper做一个移动端轮播插件。需要先异步动态加载数据后,然后使用v-for渲染节点,再执行插件的滑动轮播行为。解决这个问题,我们通过在组件中使用vm.$nextTick来解决这一需求。

1、在数据调用结束后再进行swiper初始化

  

 //调用接口查询需要循环的商品
    this.$http.get('../../../static/json/foodkind.json').then((res) => {
      this.foodArr = res.data.foodkind;
      // $nextTick,它会在数据变化以后,DOM更新以后进行回调函数
      this.$nextTick(function() {
        new Swiper('.swiper-container', {
          pagination: '.swiper-pagination',
          paginationClickable: true,
          spaceBetween: 30,
          centeredSlides: true,
          autoplay: 2500,
          autoplayDisableOnInteraction: false
        });
      })
    }, (res) => {
      console.log("error");
    })

这里还要用到$nextTick,它会在数据变化以后,DOM更新以后进行回调函数,不然的话轮播还是会出现错乱的情况

总结:

* `Vue.nextTick(callback)`,当数据发生变化,更新后执行回调。
* `Vue.$nextTick(callback)`,当dom发生变化,更新后执行的回调。

 三 vue的跨域解决

 我们在项目中,有的时候会遇到vue的跨域问题,这个时候我们要么使用jsonp的形式获取,要么使用配置vue的proxy代理的方式,前者,我还没研究懂,现在先介绍配置proxy代理的方式

dev: {
        env: require('./dev.env'),
        port: 8080,
        autoOpenBrowser: true,
        assetsSubDirectory: 'static',
        assetsPublicPath: '/',
        proxyTable: {
            '/api/**': {
                target: 'http://api.douban.com/v2', //表示你跨域请求的接口的域名
                secure: false, //如果是https接口,需要配置这个参数
                changeOrigin: true, //如果接口跨域,需要进行这个参数配置
 pathRewrite: {
 '^/api': ''
 }
},
'/users/*': {
                target: 'http://127.0.0.1:8089'
            }
        },
        // CSS Sourcemaps off by default because relative paths are "buggy"
        // with this option, according to the CSS-Loader README
        // (https://github.com/webpack/css-loader#sourcemaps)
        // In our experience, they generally work as expected,
        // just be aware of this issue when enabling this option.
        cssSourceMap: false
    }

在main.js当中可以配置一个公共的路由路径
axios.defaults.baseURL = '';
或者可以在调用该接口的时候,直接使用加上/api

 

 

 

四  proos的简单用法

 

使用 props 传递数据

 

组件实例的作用域是孤立的。这意味着不能并且不应该在子组件的模板内直接引用父组件的数据。可以使用 props 把数据传给子组件。

“prop” 是组件数据的一个字段,期望从父组件传下来。子组件需要显式地用 props 选项 声明 props:

1
2
3
4
5
6
7
Vue.component('child', {
 // 声明 props
 props: ['msg'],
 // prop 可以用在模板内
 // 可以用 `this.msg` 设置
 template: '<span>{{ msg }}</span>'
})

然后向它传入一个普通字符串:

<child msg="hello!"></child>

举例

错误写法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<!DOCTYPE html>
<html lang="en">
 
<head>
 <script type="text/javascript" src="./vue.js"></script>
 <meta charset="UTF-8">
 <title>vue.js</title>
</head>
 
<body>
<pre>
 //使用 props 传输资料予子组件
 //props , data 重复名称会出现错误
 
 
</pre>
<div id="app1">
 <child mssage="hello!"></child>
</div>
<script>
 Vue.config.debug = true;
 Vue.component('child', {
 // declare the props
 props: ['msg','nihao','nisha'],
 // the prop can be used inside templates, and will also
 // be set as `this.msg`
 template: '<span>{{ msg }}{{nihao}}{{nisha}}</span>',
 data: function() {
 return {
 mssage: 'boy'
 }
 }
 });
 var vm = new Vue({
 el: '#app1'
 })
</script>
</body>
 
</html>

正确写法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<!DOCTYPE html>
<html lang="en">
 
<head>
 <script type="text/javascript" src="./vue.js"></script>
 <meta charset="UTF-8">
 <title>vue.js</title>
</head>
 
<body>
<pre>
 //使用 props 传输资料予子组件
 //props , data 重复名称会出现错误
 
 
</pre>
<div id="app1">
 <child mssage="hello!"></child>
</div>
<script>
 Vue.config.debug = true;
 Vue.component('child', {
 // declare the props
 props: ['msg','nihao','nisha'],
 // the prop can be used inside templates, and will also
 // be set as `this.msg`
 template: '<span>{{ msg }}{{nihao}}{{nisha}}</span>'
 });
 var vm = new Vue({
 el: '#app1'
 })
</script>
</body>
 
</html>

props 传入多个数据(顺序问题)

第一种:

HTML             

1
2
3
4
5
<div id="app1">
<child msg="hello!"></child>
<child nihao="hello1!"></child>
<child nisha="hello2!"></child>
</div>

JS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Vue.config.debug = true;
Vue.component('child', {
// declare the props
props: ['msg','nihao','nisha'],
// the prop can be used inside templates, and will also
// be set as `this.msg`
template: '<span>{{ msg }}{{nihao}}{{nisha}}</span>',
/*data: function() {
return {
msg: 'boy'
}
}*/
});
var vm = new Vue({
el: '#app1'
})

结果:hello! hello1! hello2!

第二种:

HTML

1
2
3
4
5
<div id="app1">
<child msg="hello!"></child>
 <child nihao="hello1!"></child>
 <child nisha="hello2!"></child>
</div>

JS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Vue.config.debug = true;
Vue.component('child', {
// declare the props
props: ['msg','nihao','nisha'],
// the prop can be used inside templates, and will also
// be set as `this.msg`
template: '<span>123{{ msg }}{{nihao}}{{nisha}}</span>',
/*data: function() {
return {
msg: 'boy'
}
}*/
});
var vm = new Vue({
el: '#app1'
})

结果:123hello! 123hello1! 123hello2!

第三种:

HTML

1
2
3
4
5
<div id="app1">
<child msg="hello!"></child>
<child nihao="hello1!"></child>
 <child nisha="hello2!"></child>
</div>

JS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Vue.config.debug = true;
Vue.component('child', {
// declare the props
props: ['msg','nihao','nisha'],
// the prop can be used inside templates, and will also
// be set as `this.msg`
template: '<span>{{ msg }}{{nihao}}{{nisha}}123</span>',
/*data: function() {
return {
msg: 'boy'
}
}*/
});
var vm = new Vue({
el: '#app1'
})

结果:hello! 123 hello1! 123 hello2!123

第四种:

HTML                 

1
2
3
4
5
<div id="app1">
<child msg="hello!"></child>
<child nihao="hello1!"></child>
<child nisha="hello2!"></child>
</div>

JS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Vue.config.debug = true;
Vue.component('child', {
// declare the props
props: ['msg','nihao','nisha'],
// the prop can be used inside templates, and will also
// be set as `this.msg`
template: '<span>{{ msg }}123{{nihao}}{{nisha}}123</span>',
/*data: function() {
return {
msg: 'boy'
}
}*/
});
var vm = new Vue({
el: '#app1'
})

结果:hello! 123 123hello1! 123hello2!

结论: 

在props 中传入多个数据是,如果在父组件的模板类添加其他元素或者字符会有:
1-在最前面加入—每个子组件渲染出来都会在其前面加上

2-在最后面加入—每个子组件渲染出来都会在其后面加上

3-在中间加入—他前面子组件后面加上,后面的子组件后面加上

 五 proos的简单用法

ps:App.vue 父组件

  Hello.vue 子组件

复制代码
ps:App.vue 父组件
  Hello.vue 子组件
 

<!--App.vue  :-->

<template>
  <div id="app">
    <hello @newNodeEvent="parentLisen" />
  </div>
</template>

<script>
    import hello from './components/Hello'
    export default {
        name: 'app',
        'components': {
            hello
        },
        methods: {
            parentLisen(evtValue) {    
                //evtValue 是子组件传过来的值
                alert(evtValue)
            }
        }
    }
</script>


<!--Hello.vue  :-->

<template>
  <div class="hello">
    <input type="button" name="" id="" @click="chilCall()" value="子调父" /> 
  </div>
</template>

<script>
    export default {
        name: 'hello',
        'methods': {
            chilCall(pars) {
                this.$emit('newNodeEvent', '我是子元素传过来的')
            }
        }
    }
</script>
posted @ 2018-04-02 15:10  星期九  阅读(247)  评论(0编辑  收藏  举报