Vue 是當下非常流行的前端框架之一,它可以幫助我們快速建立高效且美觀的使用者介面。在本文中,我們將介紹如何使用 Vue 實現仿京東搜尋頁面。
首先,我們需要準備以下工具和技術:
使用Vue CLI 初始化一個新的專案非常簡單,只需要在命令列中執行以下命令:
vue create jd-search
這個指令會在目前目錄下建立一個名為jd-search
的項目,並自動安裝所需的依賴項。
安裝Element UI 非常簡單,只需要在命令列中執行以下命令:
npm install element-ui
安裝完成後,在main.js
中引入Element UI:
import Vue from 'vue' import ElementUI from 'element-ui' import 'element-ui/lib/theme-chalk/index.css' Vue.use(ElementUI)
在src/components
目錄下創建一個名為Search.vue
的元件。這個元件包含一個輸入框和一個搜尋按鈕,程式碼如下:
這個元件包含一個 keyword
資料屬性,用來保存使用者輸入的關鍵字。當使用者點擊搜尋按鈕或按下回車鍵時,會觸發 search
方法,將目前的 keyword
值作為參數傳遞給父元件。
在 src/components
目錄下建立一個名為 ProductList.vue
的元件。這個元件會顯示搜尋結果的商品列表,程式碼如下:
{{ product.title }}
{{ product.price }}
{{ product.description }}
這個元件接收一個名為 products
的屬性,用來顯示搜尋結果。它使用 Element UI 的 el-card
和 el-image
元件顯示商品列表,並使用 CSS Grid 實現自適應佈局。
使用 Vuex 管理應用程式的狀態非常方便。在 src/store
目錄下建立一個名為 search.js
的模組。這個模組包含以下狀態、操作和 getters:
const state = { keyword: '', products: [], }; const mutations = { updateKeyword(state, keyword) { state.keyword = keyword; }, updateProducts(state, products) { state.products = products; }, }; const actions = { async search({ commit }, keyword) { const response = await this.$axios.get('/api/search', { params: { keyword }, }); commit('updateProducts', response.data); }, }; const getters = {}; export default { namespaced: true, state, mutations, actions, getters, };
這個模組包含一個名為 search
的非同步操作,用於發送搜尋請求並更新搜尋結果。它還包含一個名為 keyword
的狀態和一個名為 products
的狀態,用於保存使用者輸入的關鍵字和搜尋結果。
建立一個名為SearchPage.vue
的頁面,它會包含Search
和ProductList
元件,並透過Vuex 管理它們之間的互動。程式碼如下:
這個頁麵包含Search
和ProductList
元件,並使用Vuex 的mapState
和mapActions
映射products
屬性和search
操作。當使用者輸入關鍵字並點擊搜尋按鈕或按下回車鍵時,會觸發 search
操作,從後端 API 取得搜尋結果,並更新 Vuex 中的 products
狀態。
在src/main.js
中設定Axios,程式碼如下:
import axios from 'axios' import VueAxios from 'vue-axios' Vue.use(VueAxios, axios) axios.defaults.baseURL = 'http://localhost:3000'
這個設定使得我們可以在應用程式中使用$axios
物件發送HTTP 請求。現在,我們可以在 search
操作中發送搜尋請求了。
至此,我們已經完成了仿京東搜尋頁面的實作。這個頁面使用了 Vue、Element UI、Axios 和 Vuex 等技術,並遵循了現代化的單頁應用程式的最佳實踐。
以上是如何使用 Vue 實現仿京東搜尋頁面?的詳細內容。更多資訊請關注PHP中文網其他相關文章!