【vue2】组件写法

7 篇文章 0 订阅
4 篇文章 0 订阅
  • 组件基本骨架
<template>
  <div class="my-component">
    <!-- 组件的 HTML 结构 -->
    <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, // 通过 props 初始化的数据
      inputValue: '', // 绑定输入框的值
      items: ['Item 1', 'Item 2', 'Item 3'] // 列表数据
    };
  },
  methods: {
    handleClick() {
      alert('按钮被点击了!');
      this.title = '标题已更新'; // 更新 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>

  1. props(组件的输入参数):父调用 输入的参数
  2. name :组件名称设置为 MyComponent,可以通过 name 来识别和复用
  3. data(组件的内部状态):定义数据,把父调用的赋值
  • 父组件调用
<template>
  <div>
    <!-- 传递 props -->
    <MyComponent initialTitle="初始标题"></MyComponent>
  </div>
</template>

<script>
import MyComponent from './MyComponent.vue';

export default {
  components: {
    MyComponent
  }
};
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值