Vuejs初步学习

2016-09-09  本文已影响113人  潇Lee

按照官网的介绍,Vuejs有两个主要的技术,第一:数据绑定;第二:组件系统;对于它的组件系统,我倒觉得不太成熟,所以,暂时就使用一下数据绑定吧,用熟一点,还是可以节省不少时间的。

数据绑定的核心优势就是,可以用逻辑代码中的数据改变直接触发页面的变化,省去了传统使用的DOM操作,因为DOM操作比较麻烦,而且重复度高,因此省去了这个步骤,还是有蛮大帮助的。再来,数据驱动视图的思想很符合逻辑,界面中的变化实际上就是数据的变化引起的,如果业务逻辑中的数据变化可以直接反映到界面上,那么只要关注业务逻辑的处理就可以了。

最简单常用的就是,界面中的一些事件触发和服务器的通信,然后服务器发送新的数据,界面根据服务器的数据更新视图,以下是示例代码:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="//cdn.bootcss.com/jquery/3.1.0/jquery.js"></script>
<script src="js/vue.js"></script>
<title>Vuejs_数据绑定测试</title>
</head>

<body>
<div id="app">
<div>接收到的消息:{{{message}}}</div>
<button @click="receiveMessage">开始接收消息</button>
</div>
</body>
<script>
 var vm = new Vue({
   el: '#app',
   data: {
   message: '<p></p>'
 },
 methods: {
   receiveMessage: function () {
     /*模拟服务器返回延迟*/
     setTimeout(function () {
     $.get("http://localhost:8001", function (data) {
     console.log(data);
     /*这里不能使用this.message,$.get()方法里面的this指向不是vue实例*/
     vm.message = vm.message.concat(data.result);
     }); }, 200);
   }
  }
 });
</script>
</html>

服务器端代码(node.js)

var http = require('http');
console.log('test node.js http_server...');
http.createServer(function (request, response) {
    var data = {'result': '<p>来自服务器端代码片段</p>'};
    response.writeHead(200, {'Content-Type': 'application/json;charset=utf-8', 'Access-Control-Allow-Origin': '*'});
    response.end(JSON.stringify(data));
}).listen(8001);

console.log('node.js server run at http://localhost:8001/...');
上一篇 下一篇

猜你喜欢

热点阅读