Share&Joy

Ginger' Blog


  • 首页
  • 归档
  • 标签
  •   

© 2018 1-riverfish

Theme Typography by Makito

Proudly published with Hexo

Moon框架入门教程2

发布于 2017-08-30 tech Moon 

Moon框架入门教程2

Instance实例

The root Moon instance is the core of your application, this is where any top level data should be defined, and it should be mounted on the root element that contains all of your components, directives, and templates.

抱歉不能准确翻译


初始化

1
2
3
4
new Moon(
{
//options
});

通过关键字new新建 Moon 实例,其中包含实例的所有选项.实例可以不包含任何选项,但如果选项中包含el,那么实例将被绑定到这个元素上.如果没有提供el选项,app必须被手动绑定,例如

1
app.mount('#app');

如果你提供一个template选项,Moon 将替代元素的outerHTML进行编译,例如

1
2
3
new Moon({
template: '<div>Content</div>'
});

一个MOON组件接受常规实例的所有选项,除了el


数据

实例中的所有数据应该被提供在data选项中,这些数据可以通过模板来获得.这些数据的属性是reactive(活性的),用.set更改数据会立即在DOM中更新


方法

当你想要重用代码中特定的行为时,可以调用方法来替代增加一个计数器(小编理解为一个特定行为,比如在app6的例子中count+1)

方法中的this是一个指向实例的引用(我有感觉,js和C++有某种关系),所以你可以this.set.

这也意味着,你必须用app.callMethod当你不得不手动调用他的时候.

1
2
3
4
5
6
7
8
9
10
11
const app = new Moon({
data: {
count: 0
},
methods: {
increment: function (){
this.set('count',this.get('count')+1);
}
}
app.callMethod('increment');
});

方法在模板中也可以使用,即使需要调用任何函数

1
2
3
4
<div id='app'>
<p>{{reverse(msg)}}</p>
<p>{{reverse("racecaR")}}
</div>
1
2
3
4
5
6
7
8
9
10
11
const app = new Moon({
el: '#app',
data: {
msg: '!nooM olleH'
},
methods: {
reverse: function (str){
return str.split('').reverse().join('');
}
}
});

Computed Properties

如果你有一个依赖其他数值并返回动态结果的value,你应该用到 a computed property,computed property分析他们的依赖关系并只在需要时运行.例如

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const app = new Moon({
el: '#app',
data: {
msg: 'Hello Moon!',
count: 0
},
computed: {
reversedMsg: {
get: function() {
return this.get('msg').split('').reverse().join('');
}
}
}
});

app.set('msg','New Message');//将会引起 ‘reversedMsg’ 进行求值(有一个联动)
app.set('count',1);// 'reversedMsg‘将会被贮藏
//这个地方有些疑问,理解的不好

This caching behavior efficiently prevents any complex computations to be run only when needed. If a property that the computed property depends on is updated, then the computed property is evaluated again and analyzed for new dependencies.

大概理解了一下,意思是 当一个 computed property中的 property所依赖的property发生了改变,computed property 会再次进行求值,而不会累加成复杂的计算


生命周期

类似于 React 和 Vue ,Moon调用 lifecycle hooks贯穿你的实例和组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
new Moon({
hooks: {
init: function(){
// 当第一次创建时被调用
},
mounted: function(){
// called when element is mounted and the first build has been run
},
updated: function(){
// called every time data is updated
},
destroyed: function() {
// called when it is destroyed, the component might be removed
// from the DOM
}
}
})

正如同你可以手动挂载实例,你也可以

app.destroy();

这会销毁实例

  • 阻止活性更新
  • 拆卸事件监听器

你也可以重新挂载,然后数据就会被重新存储并且具有活性

晚上遇到了一点问题,无法进入Linux系统,王哥我社长说了一句挺在理,出了问题就重启,再不行就是权限的问题,问题解决办法.

Any question please contack 1-riverfish

分享到 

 上一篇: Moon框架入门教程3 下一篇: Moon框架入门教程1 

© 2018 1-riverfish

Theme Typography by Makito

Proudly published with Hexo