<template><div class="my-component"><h1>{{ title }}</h1><button @click="handleClick">点击我</button><input v-model="inputValue" placeholder="请输入内容" /><ul><li v-for="(item, index) in items" :key="index">{{ item }}</li></ul></div>
</template><script>
export default {name: 'MyComponent', props: {initialTitle: {type: String,default: '默认标题'}},data() {return {title: this.initialTitle, inputValue: '', items: ['Item 1', 'Item 2', 'Item 3'] };},methods: {handleClick() {alert('按钮被点击了!');this.title = '标题已更新'; }}
};
</script><style scoped>
.my-component {padding: 20px;background-color: #f9f9f9;
}.my-component h1 {color: #333;
}.my-component button {padding: 10px 20px;background-color: #42b983;color: white;border: none;border-radius: 5px;cursor: pointer;
}.my-component button:hover {background-color: #38a169;
}
</style>
props
(组件的输入参数):父调用 输入的参数name
:组件名称设置为 MyComponent
,可以通过 name
来识别和复用data
(组件的内部状态):定义数据,把父调用的赋值
<template><div><MyComponent initialTitle="初始标题"></MyComponent></div>
</template><script>
import MyComponent from './MyComponent.vue';export default {components: {MyComponent}
};
</script>