vue3 taro小程序封装组件 用代码举例
时间: 2023-08-31 20:16:43 浏览: 30
好的,下面是一个简单的示例:
```vue
<template>
<div class="my-component">
<h2>{{ title }}</h2>
<p>{{ content }}</p>
<button @click="handleClick">{{ buttonText }}</button>
</div>
</template>
<script>
export default {
name: 'MyComponent',
props: {
title: {
type: String,
required: true
},
content: {
type: String,
default: ''
},
buttonText: {
type: String,
default: 'Click me'
}
},
methods: {
handleClick() {
this.$emit('button-click');
}
}
};
</script>
<style scoped>
.my-component {
border: 1px solid #ccc;
padding: 10px;
}
</style>
```
这是一个名为 `MyComponent` 的组件,它有三个属性:`title`、`content` 和 `buttonText`,它们分别表示标题、内容和按钮文本。
这个组件还有一个按钮,当点击它时会触发一个 `button-click` 事件,父组件可以监听这个事件来执行一些操作。
在使用这个组件时,你需要在父组件中注册它:
```vue
<template>
<div class="parent-component">
<my-component
title="Hello World"
:content="message"
@button-click="handleButtonClick"
/>
</div>
</template>
<script>
import MyComponent from '@/components/MyComponent.vue';
export default {
name: 'ParentComponent',
components: {
MyComponent
},
data() {
return {
message: 'This is some content'
};
},
methods: {
handleButtonClick() {
alert('Button clicked!');
}
}
};
</script>
```
在这个例子中,我们在父组件中引入了 `MyComponent`,然后将它作为一个子组件使用。我们传递了一些属性和一个事件监听器,当按钮被点击时会触发 `handleButtonClick` 方法。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)