Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
TANG edited this page Oct 14, 2017 · 17 revisions

组件布局

sugar 的组件布局有三种形式:字符串布局、外部模板布局和文档原有模板布局。

字符串布局

直接把布局字符串当做配置参数 view 的值传入即可:

var MyComponent = sugar.Component.extend({
	init: function (config) {
		this.Super('init', config, {
			view: '<h1>title</h1>'
		});
	}
});

外部模板布局

将模板的静态文件地址指定到配置参数 template 即可,sugar 内部使用 Ajax 请求模板地址,将返回的结果添加到布局中,另外,可以用 tplParam 来添加请求的参数:

var MyComponent = sugar.Component.extend({
	init: function (config) {
		this.Super('init', config, {
			template: 'path/to/component.html',
			tplParam: {
				nocache: Date.now()
			}
		});
	}
});

path/to/component.html 文件:

<h1>title</h1>

注意:template 的布局内容优于 view 的内容,如同时指定只渲染 template 中的内容。

文档原有模板

将组件的布局预先写在 <body></body> 中,然后在组件配置参数中指定 target 参数为组件布局的选择器即可:

<body>
	<div id="app">
		<h1>title</h1>
	</div>
</body>
var MyComponent = sugar.Component.extend({
	init: function (config) {
		this.Super('init', config, {
			target: '#app'
		});
	}
});

注意:这种组件布局形式适用于单个功能组件,这种布局形式的组件不建议进行复用和继承。

使用 MVVM

MVVM 在 sugar 中是一个独立的功能库,实现数据绑定 + 视图刷新和表单元素双向数据绑定。在组件内部使用 MVVM 只要指定数据模型字段参数 model 即可,此外还支持以下声明字段:

  • 计算属性对象 computed
  • 事件函数对象 methods
  • 批量 watch 对象 watches
  • 统一变更回调函数 watchAll
  • 自定义指令刷新函数对象 customs
  • v-if/v-for 片段更新钩子函数对象 hooks
  • 手动挂载编译(开发者控制编译时机) lazy

此外,watches, methodswatchAll 中所有函数的上下文都会指向组件本身,具体的使用可参见 MVVM 实例与指令

<body>
	<div id="app">
		<h1>{{ title }}</h1>
		<h2>{{ bookTitle }}</h2>
		<ul>
			<li v-for="item in items">
				{{ item.text }}
			</li>
		</ul>
	</div>
</body>
var MyComponent = sugar.Component.extend({
	init: function (config) {
		this.Super('init', config, {
			target: '#app',
			model: {
				title: 'xxdk',
				items: [
					{text: 'aaa'},
					{text: 'bbb'},
					{text: 'ccc'}
				]
			},
			computed: {
				bookTitle: function () {
					// 计算属性必须为一个取值函数
					// 并且必须有计算属性的返回值
					// 取值函数的执行上下文(this)就是 model
					return "《" + this.title + "》";
				}
			},
			methods: {},
			watches: {},
			watchAll: function (param, newVal, oldVal) {},
			customs: {},
			hooks: {},
			lazy: false
		});
	}
});
sugar.core.create('my-component', MyComponent);

MVVM 编译后的结果:

<body>
	<div id="app">
		<h1>xxdk</h1>
		<h1>《xxdk》</h1>
		<ul>
			<li>aaa</li>
			<li>bbb</li>
			<li>ccc</li>
		</ul>
	</div>
</body>

更多 MVVM 指令参考 MVVM 实例与指令


上一篇:组件定义与创建

下一篇:组件的复用

Clone this wiki locally

AltStyle によって変換されたページ (->オリジナル) /