如何通过Vue.js和最少的精力为您的网站加电

by Ondřej Polesný

通过OndřejPolesný

如何通过Vue.js和最少的精力为您的网站加电 (How to power up your website with Vue.js and minimal effort)

You have a static website and you know which framework fits you and your project the best. But how do you integrate the framework into the website? How do you split the design into components? How do you handle routing between pages? How do you define where child pages should display their specific content?

您拥有一个静态网站,并且知道哪种框架最适合您和您的项目。 但是如何将框架集成到网站中? 您如何将设计分成多个部分? 您如何处理页面之间的路由? 您如何定义子页面应在何处显示其特定内容?

Making a website dynamic is a very exciting step in its development. It feels like when you install a game and you launch it for the first time, or when you buy a new phone and unbox it. Vue.js helps you achieve this moment very quickly. Creating components and putting them together is like building your website out of Lego pieces. Let’s get to it and have fun!

使网站动态化是其发展中非常激动人心的一步。 感觉就像是在安装游戏并首次启动游戏时,或者在购买新手机并拆箱后。 Vue.js可帮助您快速实现这一目标。 创建组件并将它们组合在一起就像使用Lego块构建网站一样。 让我们开始吧,玩得开心!

整合Vue.js (Integrating Vue.js)

Having picked the right framework for my website, I can start integrating all the parts together. What are those parts?

在为我的网站选择了正确的框架之后,我可以开始将所有部分集成在一起。 这些部分是什么?

  • HTML template — markup

    HTML模板-标记
  • Website logic — Vue.js and its components

    网站逻辑-Vue.js及其组件
  • Content for all the components — all services providing data via their APIs

    所有组件的内容-所有服务均通过其API提供数据

Have you ever heard about JAMstack? It’s a modern web development architecture based on these three parts that I outlined above. There are some additional best practices on their website, but we will get to those later.

您听说过JAMstack吗? 这是一种现代的Web开发体系结构,基于我上面概述的这三个部分。 他们的网站上还有一些其他最佳做法,但我们稍后会介绍。

Let’s get started with the website development. First, we need to add Vue.js library into our main HTML template. If you plan to have multiple pages, you will also need Vue.js router. Add both before the ending of the Head tag.

让我们开始进行网站开发。 首先,我们需要将Vue.js库添加到我们的主要HTML模板中。 如果您打算有多个页面,则还需要Vue.js路由器。 在Head标记的末尾添加两者。

...  <! — development version, includes helpful console warnings →  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>  <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script></head>...

Second, we need to pick an element that wraps up all the Vue.js functionality. Vue.js does not necessarily need to control your whole website, but only a small part of it. However, in our case we want Vue.js to control the whole page. Therefore, we can pick the topmost element and assign an ID to it if it does not have one yet.

其次,我们需要选择一个包含所有Vue.js功能的元素。 Vue.js不一定需要控制您的整个网站,而只是其中的一小部分。 但是,在我们的情况下,我们希望Vue.js控制整个页面。 因此,我们可以选择最上面的元素,如果还没有ID,则为其分配一个ID。

...<body class="is-preload">  <div id="page-wrapper">    <header id="header" class="alt">...

Good job! We now have the main page ready for Vue.js components.

做得好! 现在,我们已经为Vue.js组件准备好了主页。

布置组件 (Laying out the components)

When you start cutting your website into smaller pieces, the process is to some extent always the same regardless of technology or framework used. There are always parts of the page that will be displayed on all pages, like the main menu and footer. These form your master page, or in our case the master template. Let’s take a look at how those parts look like on my design.

当您开始将网站切成小块时,无论使用什么技术或框架,该过程在一定程度上始终是相同的。 页面的某些部分始终会显示在所有页面上,例如主菜单和页脚。 这些构成您的母版页,或者在我们的情况下构成母版模板。 让我们看看这些部分在我的设计中的样子。

  1. Header including the main menu

    标题包括主菜单
  2. Footer including the contact form

    页脚包括联系表格

Everything else that is in between is interchangeable based on page context. In other words, the highlighted parts always stay the same. It’s the middle that changes based on the URL.

两者之间的其他所有内容都可以根据页面上下文互换。 换句话说,突出显示的部分始终保持不变。 它是根据URL进行更改的中间部分。

First of all let’s create two empty files:

首先,让我们创建两个空文件:

  • app.js

    app.js
  • components.js

    components.js

Put them in the folder assets/js (you can pick any other folder if you prefer) and reference them in the website. Add these assets before the ending of the Body tag. If there is any other JavaScript functionality, make sure to include these files before any other that may change the HTML markup.

将它们放在文件夹assets/js (如果愿意,可以选择其他任何文件夹),并在网站中引用它们。 在“正文”标签的末尾添加这些资产。 如果还有其他JavaScript功能,请确保先包含这些文件,然后再包含其他可能更改HTML标记的文件。

...<script src="assets/js/components.js"></script><script src="assets/js/app.js"></script>...

On my website there are 3 pages, so in total I will have 3 URLs and 3 main components on my page:

在我的网站上有3个页面,因此我的页面总共有3个URL和3个主要组成部分:

  • / - Homepage

    / - 主页
  • /blog - Blog page

    / blog-博客页面
  • /about - About me page

    / about-关于我的页面

主模板 (Master template)

The main HTML file will be used as the master template for the whole website. Therefore we need to remove all page-specific content. We leave only those elements that will be displayed on all pages throughout the website. When I do that and open the page in the browser, I see this:

主HTML文件将用作整个网站的主模板。 因此,我们需要删除所有页面特定的内容。 我们仅保留那些将显示在网站所有页面上的元素。 当我这样做并在浏览器中打开页面时,我看到以下内容:

There is a header with the menu (1), contact form with footer (2) and the empty yellow place is where the content of all my child pages will appear. Remember that we included Vue.js router along with the main Vue.js framework library? The router is going to handle all navigation for us. It will ensure that each child page is rendered in this master template. We need to tell the router where to render them. In your HTML code find a place marked by the yellow stripe and add the following component there:

有一个带有菜单的标题(1),带有页脚的联系表单(2),黄色的空白位置是我所有子页面的内容出现的地方。 还记得我们在主Vue.js框架库中包含了Vue.js路由器吗? 路由器将为我们处理所有导航。 它将确保在此主模板中呈现每个子页面。 我们需要告诉路由器在哪里渲染它们。 在您HTML代码中找到一个带有黄色条纹标记的位置,并在其中添加以下组件:

...<router-view></router-view>...

This tells the router to use this place for rendering child pages and their components. We also need to adjust links in main navigation from usual a tags to router links. Here is my implementation:

这告诉路由器将这个位置用于呈现子页面及其组件。 我们还需要将主导航中的链接从通常的a标签调整为路由器链接。 这是我的实现:

... <li><router-link to="/">Home</router-link></li> <li><router-link to="/blog">Blog</router-link></li> <li><router-link to="/about">About</router-link></li>...

If there are any other parameters on your a tags, you can use them with router-link tags too. Vue.js router will make sure they appear in the final HTML code.

如果您a标签上还有其他参数,您也可以将其与router-link标签一起使用。 Vue.js路由器将确保它们出现在最终HTML代码中。

Congratulations, your master template is finished.

恭喜,您的主模板已完成。

子页面 (Child pages)

Because my website is small and we are aiming for an easy implementation, child pages will not have their physical interpretation. However, if you have a lot of pages and want to separate them using physical files, it is possible. In that case I suggest using a compiler to generate one final minimized JavaScript file of your implementation.

由于我的网站很小,并且我们的目标是易于实施,因此子页面将没有物理解释。 但是,如果您有很多页面,并希望使用物理文件将它们分开,则可以这样做。 在那种情况下,我建议使用编译器来生成实现的最终最小化JavaScript文件。

First of all, let’s initialize our Vue.js application and routes in app.js file. Routes are coming directly from the list of pages above. The implementation should look like this:

首先,让我们初始化Vue.js应用程序并在app.js文件中路由。 路线直接来自上面的页面列表。 实现应如下所示:

const router = new VueRouter({ routes: [  { path: '/', component: Home },  { path: '/blog', component: Blog },  { path: '/about', component: About } ]})const app = new Vue({ el: '#page-wrapper', router})

We create the router instance and pass it URLs of all our pages and components names. We do not have those components yet, so I just used names of corresponding pages. We will create components with the same names later.

我们创建路由器实例,并将所有页面和组件名称的URL传递给它。 我们还没有那些组件,因此我只使用了相应页面的名称。 稍后我们将创建具有相同名称的组件。

Every Vue.js application is brought to life by creating an instance of the Vue class and connecting it to an element. In my case it is a div with id page-wrapper — the top level element just under the body tag. The instance also needs to know we want to use Vue.js router. That is why the router instance is passed into the main instance.

通过创建Vue类的实例并将其连接到元素,可以使每个Vue.js应用程序栩栩如生。 在我的情况下,它是一个ID为page-wrapper的div,它是位于body标签下的顶级元素。 该实例还需要知道我们要使用Vue.js路由器。 这就是将路由器实例传递到主实例的原因。

The last thing we need to do is to define components for each page. Note that we need to create them before the definition of the Vue application, otherwise they will not be known to Vue.js.

我们要做的最后一件事是为每个页面定义组件。 请注意,我们需要在定义Vue应用程序之前创建它们,否则Vue.js不会知道它们。

Remember the deleted code from the master template? That is the content of our homepage component. Let’s define it:

还记得从主模板删除的代码吗? 这就是我们主页组件的内容。 让我们定义一下:

const Home = { template: `  <div>   <section id="banner">    <div class="inner">     <div class="logo">     ...     </div>     <h2>Ondrej Polesny</h2>     <p>Developer Evangelist + dog lover + freelance bus driver</p>    </div>   </section>   <section id="wrapper">    <div>     <section id="one" class="wrapper spotlight style1">      <div class="inner">       <router-link to="/about" class="image"><img src="images/pic01.png" alt="" /></router-link>       <div class="content">        <h2 class="major">Kentico</h2>        <p>...</p>        <router-link to="/about" class="special">Continue</router-link>       </div>      </div>     </section>     <section id="two" class="wrapper alt spotlight style2">     ...     </section>     <section id="three" class="wrapper spotlight style3">     ...     </section>     <section id="four" class="wrapper alt style1">     ...     </section>     <div class="inner">      <div>       <h2 class="major">Latest blog posts</h2>       <p>...</p>       ... <!-- list of blogs -->      </div>     </div>     <ul class="actions">      <li><a href="/blog" class="button">See all</a></li>     </ul>    </div>   </section>  </div>`}

You see it is a lot of HTML markup and it makes our app.js file quite big and unreadable. Moreover, some content is also displayed on other pages. For example the list of blog articles or texts about me.

您会看到它是很多HTML标记,它使我们的app.js文件变得很大app.js可读。 此外,某些内容也会显示在其他页面上。 例如,博客文章列表或有关我的文本。

组件 (Components)

This is where components come into the mix. Components represent pieces of reusable content that can be separated out. They can also contain functionality. Examples are gathering content from external services or rewriting content based on user actions. They can also perform some calculations. Let’s take a look at how I optimized the homepage to use components:

这是组件混合在一起的地方。 组件代表了可以分离的可重用内容。 它们还可以包含功能。 例如从外部服务收集内容或根据用户操作重写内容。 他们还可以执行一些计算。 让我们看一下我如何优化主页以使用组件:

const Home = { template: `  <div>   <banner></banner>   <section id="wrapper">    <about-overview></about-overview>    <section id="four" class="wrapper alt style1">     <div class="inner">      <div>       <h2 class="major">Latest blog posts</h2>       <p>...</p>       <blog-list limit="4"></blog-list>       <ul class="actions">        <li><a href="/blog" class="button">See all</a></li>       </ul>      </div>     </div>    </section>   </section>  </div>`}

It is important to identify the components correctly. They need to be independent and cover specific functionality or markup. Take a look at how I separated them out:

正确识别组件很重要。 它们需要独立并且涵盖特定的功能或标记。 看一下我如何将它们分开:

I identified 3 components:

我确定了3个组成部分:

  • Banner (1)

    标语(1)
  • About overview (2)

    关于概述(2)
  • Blog list (3)

    博客列表(3)

Note that some controls are outside of the yellow areas that mark the respective components. For example, look at the Blog list component. You see that the button “See all”, the paragraph introducing the section and its header, are excluded from the component. The reason is that the Blog list component will also be used on the Blog page. These texts will be different and the button “See all” will not be displayed at all. Therefore the component should include only reusable pieces of content and markup.

请注意,某些控件在标记相应组件的黄色区域之外。 例如,查看博客列表组件。 您将看到“查看全部”按钮(介绍该部分及其标题的段落)已从组件中排除。 原因是Blog列表组件也将在Blog页面上使用。 这些文本将有所不同,并且“查看全部”按钮将根本不会显示。 因此,该组件应仅包含可重用的内容和标记。

I added the definitions of these components to the components.js file. They can be used independently, so if you want to separate them further, you can.

我将这些组件的定义添加到components.js文件中。 它们可以独立使用,因此,如果您想进一步分离它们,可以使用。

Banner is the simplest of these components. It does not contain any functionality, just HTML markup. See how it looks like below:

标语是这些组件中最简单的。 它不包含任何功能,仅包含HTML标记。 如下所示:

Vue.component('banner', { template: `  <section id="banner">   <div class="inner">    <div class="logo">     <span class="icon">      <img src="images/profile-picture.jpg" alt="" />     </span>    </div>    <h2>Ondrej Polesny</h2>    <p>Developer Evangelist + dog lover + freelance bus driver</p>   </div>  </section>` })

Every component needs to have a unique name (banner) and a template, which is just HTML markup. Usually components also contain data and other functions they need for their functionality. Take a look at the Blog list component:

每个组件都需要有一个唯一的名称(横幅)和一个模板,这只是HTML标记。 通常,组件还包含其功能所需的数据和其他功能。 看一下Blog列表组件:

Vue.component('blog-list', { props: ['limit'], data: function(){  return {   articles: [    {     url: 'https://medium.com',     header: 'How to start creating an impressive website for the first time',     image: 'https://cdn-media-1.freecodecamp.org/images/1*dVlw9tLq4lVaXrGG0gZc8Q@2x.png',     teaser: `OK, so you know you want to build a website. You have an idea how it should look like and what content it should display. You are sure that it should be fast, eye-pleasing, gain a lot of traction, and attract many visitors. But how do you create that? What are the trends around building websites these days? How are others building successful websites and where should YOU start? Let's give you a head start!`    },    …   ]  } }, template: `  <section class="features">   <article v-for="article in articles">    <a :href="article.url" class="image"><img :src="article.image" alt="" /></a>    <h3 class="major">{{article.header}}</h3>    <p>{{article.teaser}}</p>    <a :href="article.url" class="special">Continue reading</a>   </article>  </section>`})

In the scope of the Blog list component, I want to list latest blog posts. I also want to be able to limit the number of posts displayed on the home page to only the 4 latest articles. Thus I introduced a limit property. I will use it later when the content comes from the content service. The limit will be set in markup when using the component: <blog-list limit="4">.

在博客列表组件的范围内,我想列出最新的博客文章。 我还希望能够将主页上显示的帖子数限制为仅4条最新文章。 因此,我引入了limit属性。 当内容来自内容服务时,我将在以后使用它。 使用以下组件时,将在标记中设置该限制: <blog-list limit=" 4”>。

In the template (markup) there is a simple v-for cycle that iterates over an array of articles. The colon :href before any attribute means it will be resolved by Vue.js to a specified variable, for example article URL. Curly brackets {{article.teaser}} have the same effect.

在模板(标记)中,有一个简单的v-for 遍历一系列文章的循环。 任何属性之前的冒号:href表示Vue.js会将其解析为指定的变量,例如文章URL。 花括号{{article.teaser}}具有相同的效果。

The articles are defined in the data property within an object. Later I will show you how to store this content outside of a component, in a headless CMS. That is a content service in the cloud. But don’t worry, no money will be spent as we will use the free plan of the headless CMS Kentico Cloud.

文章在对象的data属性中定义。 稍后,我将向您展示如何在无头CMS中将该内容存储在组件之外。 那是云中的内容服务。 但是不用担心,因为我们将使用无头CMS Kentico Cloud的免费计划,所以不会花任何钱。

The last component “About overview” looks very similar. So let’s skip it for now. Let’s take a look at how to glue components and pages together and create two still missing pages — About and Blog.

最后一个组件“关于概述”看起来非常相似。 现在让我们跳过它。 让我们看一下如何将组件和页面粘合在一起,以及创建两个仍然缺少的页面-About和Blog。

创建其他页面 (Creating other pages)

These two pages — About and Blog — will be created the same way as we created the Home page. Note that we are not really creating components, but pages. Therefore there will be no Vue.component() definition, but a simple object with one property — template. These objects will go into the app.js file. Let’s take a look at the Blog page:

这两个页面-关于和博客-将以与创建主页相同的方式创建。 请注意,我们并不是真正在创建组件,而是在创建页面。 因此,将没有Vue.component()定义,而是具有一个属性-模板的简单对象。 这些对象将进入app.js文件。 让我们看一下Blog页面:

const Blog = { template: `  <section id="wrapper">   <header>    <div class="inner">     <h2>Blog posts</h2>     <p>Here you can see list of all blog posts that I published.</p>    </div>   </header>   <div class="wrapper">    <div class="inner">     <blog-list></blog-list>    </div>   </div>  </section>`}

You see, this page got really simple as the Blog list component could have been reused.

您会看到,此页面非常简单,因为可以重新使用Blog列表组件。

Remember when we were creating routes for Vue.js router before? We connected each route with a non-existing identifier described as a component.

还记得我们之前为Vue.js路由器创建路由的时候吗? 我们将每条路线与描述为组件的不存在的标识符相连。

const router = new VueRouter({ routes: [  { path: '/', component: Home },  { path: '/blog', component: Blog },  { path: '/about', component: About } ]})

In reality, these components are pages. Pages that we just now created as simple objects and assigned them to constants. Note that name of these constants must match names of components of respective routes. For example, a page on the /blog route needs to be defined as object in the constant Blog.

实际上,这些组件是页面。 我们现在将页面创建为简单对象并将其分配给常量。 请注意,这些常量的名称必须与相应路由的组件名称匹配。 例如,需要将/blog路由上的页面定义为常量Blog object。

整理起来 (Finishing up)

When you have all your components and pages defined, open your master template and see the results. The website is dynamic even though we did not use any server-side rendering technology. Both routing and rendering of components are done by Vue.js.

定义完所有组件和页面后,打开主模板并查看结果。 即使我们没有使用任何服务器端渲染技术,该网站也是动态的。 组件的路由和渲染均由Vue.js完成。

One last tip: if you see an incomplete website, chances are you have a typo in one of the JavaScript files. Open up your browser’s console by hitting F12 (or CTRL+SHIFT+C) and switch to the Console tab. You will see the cause of the error there.

最后一个提示:如果您看到一个不完整的网站,则可能是其中一个JavaScript文件中有错字。 按下F12 (或CTRL+SHIFT+C )打开浏览器的控制台,然后切换到“控制台”选项卡。 您将在那里看到错误的原因。

Congratulations! You have just made your website dynamic. In the next article I will show you how to separate content from components and create a true microservice architecture with headless CMS.

恭喜你! 您刚刚使网站变得动态。 在下一篇文章中,我将向您展示如何从组件中分离内容并使用无头CMS创建真正的微服务体系结构。

  1. How to start creating an impressive website for the first time

    如何首次开始创建令人印象深刻的网站

  2. How to decide on the best technology for your website?

    如何为您的网站选择最佳技术?

  3. How to power up your website with Vue.js and minimal effort

    如何通过Vue.js和最少的精力为您的网站加电

  4. How to Mix Headless CMS with a Vue.js Website and Pay Zero

    如何将无头CMS与Vue.js网站混合并支付零费用

  5. How to Make Form Submissions Secure on an API Website

    如何在API网站上确保表单提交的安全

  6. Building a super-fast and secure website with a CMS is no big deal. Or is it?

    用CMS构建超快速,安全的网站没什么大不了的。 还是?

  7. How to generate a static website with Vue.js in no time

    如何立即使用Vue.js生成静态网站

  8. How to quickly set up a build process for a static site

    如何快速设置静态站点的构建过程

翻译自: https://www.freecodecamp.org/news/how-to-power-up-your-website-with-vue-js-and-minimal-effort-dc8042cc383c/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值