4 迁移页面/组件
假如 weex 项目中 src/components/HelloWorld.vue
组件内有个子组件 comp
;
首先我们修改下这两个组件,使其有一些简单的新增todolist的功能
HelloWorld.vue
<template>
<div class="demo-com">
<div class="title">this is helloworld</div>
<comp @parentClick="handleParentClick"></comp>
</div>
</template>
<script>
import lodash from 'lodash'
import comp from './comp.vue';
export default {
name: 'HelloWorld',
data () {
return {
}
},
methods:{
handleParentClick(...args){
console.log('parentClick',...args)
}
},
components:{
comp
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.demo-com {
display: flex;
flex-direction: column;
align-items: center;
height:400px;
justify-content: center;
}
.title {
align-self: center;
color: #61c7fc;
font-size: 72px;
margin-bottom: 20px;
}
</style>
comp.vue
<template>
<div>
<input type="text" v-model="todo">
<div v-for="(item,index) in todos">
{{item}}
</div>
<div @click="addTodo">addTodo</div>
<div @click="handleClick">触发父组件事件</div>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data () {
return {
todo:'todo1',
todos:[],
}
},
methods:{
addTodo(){
this.todos.push(this.todo)
},
handleClick(){
console.log('click');
this.$emit('parentClick',{
value:1,
})
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
4.1 新建页面/组件
cml init page
输入 HelloWorld
利用脚手架命令,在src/pages
中生成对应的页面
<template>
<view><text>Hello Chameleon!</text></view>
</template>
<script>
class HelloWorld {
//...
}
export default new HelloWorld();
</script>
<style>
</style>
<script cml-type="json">
{
"base": {
"usingComponents": {}
},
"wx": {
"navigationBarTitleText": "index",
"backgroundTextStyle": "dark",
"backgroundColor": "#E2E2E2"
},
"alipay": {
"defaultTitle": "index",
"pullRefresh": false,
"allowsBounceVertical": "YES",
"titleBarColor": "#ffffff"
},
"baidu": {
"navigationBarBackgroundColor": "#ffffff",
"navigationBarTextStyle": "white",
"navigationBarTitleText": "index",
"backgroundColor": "#ffffff",
"backgroundTextStyle": "dark",
"enablePullDownRefresh": false,
"onReachBottomDistance": 50
}
}
</script>
cml init component
选择 Normal component
输入 comp
生成的组件如下
<template>
<view><text>Hello Chameleon!</text></view>
</template>
<script>
class Comp {
//...
}
export default new Comp();
</script>
<style>
</style>
<script cml-type="json">
{
"base": {
"usingComponents": {}
}
}
</script>
4.2 迁移组件引用
假设weex项目src/components/HelloWorld.vue
中引用了其他组件 import comp from './comp.vue'
;
对应到cml项目 组件需要在 usingComponents
引用,不需要在配置 components
字段
修改src/pages/HelloWorld/HelloWorld.cml
页面配置,如下:
<script cml-type="json">
{
"base": {
"usingComponents": {
"comp":"/components/comp/comp"
}
}
}
</script>
总结:
1 router.js
中对应的组件需要通过 cml init page
生成,然后在 router.config.js
中配置对应路由
2 组件内部引用的子组件要通过cml init component
生成,然后通过 usingComponents
字段去引用
3 组件内引用的其他js库,比如import lodash from 'lodash'
仍然通过import
的形式引用