本篇将介绍san的基础知识,包括双向绑定、父子组件通信、动态组件通信。更加详细的可看官方文档。
双向绑定
在san中,通过:{= value =} 实现双向绑定。请看实例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>双向绑定</title>
</head>
<body>
<script src="https://unpkg.com/san@latest"></script>
<script>
var MyApp = san.defineComponent({
template:
'<div>'
+ '请输入值: <input value="{= word =}" placeholder="请输入">'
+ '<h2>输入的值: {{word}}</h2>'
+ '</div>'
,
initData: function () {
return {
word: ''
};
}
});
var myApp = new MyApp();
myApp.attach(document.body);
</script>
</body>
</html>
父子组件通信
- 父组件向子组件传值
父组件通过双向绑定,向子组件传值;
// 父组件中,将值绑定在子组件上
<my-card title="{{title}}"></my-card>
// 子组件中获取
this.data.get('title')
- 子组件向父组件传值
子组件通过 this.fire('change', value),向父组件传值;父组件通过监听事件接收。
// 子组件中, 通过fire传值给父组件
this.fire("change", title)
// 父组件中,监听change事件
<my-card on-change="getTitle"></my-card>
// 事件监听, 接收子组件的值
getTitle:function(value){
var newWord = value
this.data.set("word", newWord)
}
详情请看完整例子:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>父子组件通信</title>
<link rel="stylesheet" href="./static/style.css">
</head>
<body>
<script src="https://unpkg.com/san@latest"></script>
<script>
var Child = san.defineComponent({
template:
'<div class="card">'
+ '<p class="card-title">{{title}}</p>'
+ '<p class="card-content">{{content}}</p>'
+ '<button class="card-btn" on-click="change">点我</button>'
+ '</div>'
,
initData: function () {
return {
title: "child title",
content: "child content",
};
},
change:function(){
var title = this.data.get("title") // 获取父组件传的值
this.fire("change", title) // 传值给父组件
}
});
var Parent = san.defineComponent({
template:
'<div class="parent">'
+ '<p class="top">看这里:{{word}}</p>'
+ '<my-card title="{{title[0]}}" content="{{content[0]}}" on-change="getTitle"></my-card>'
+ '<my-card title="{{title[1]}}" content="{{content[1]}}" on-change="getTitle"></my-card>'
+ '</div>'
,
components: {
'my-card': Child
},
initData: function () {
return {
word:"demo of san",
title:[],
content:[]
};
},
attached:function(){
let _this = this
setTimeout(function(){
_this.data.push("title", 'san') // 数组需要使用push,视图才会变化
_this.data.push("title", 'yongchaoo')
_this.data.push("content", 'js frame')
_this.data.push("content", 'loving coding')
}, 3000)
},
// 事件监听, 接收子组件的值
getTitle:function(value){
var newWord = value
this.data.set("word", newWord)
}
});
var Parent = new Parent();
Parent.attach(document.body);
</script>
</body>
</html>
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。