title: Vue router mounted twice when switching page
body: <p>I'm using <a href="https://router.vuejs.org/en/" rel="nofollow noreferrer">vue-router</a> for switching pages. Now I have two Vue documents:</p>
  
  <ul>
  <li>Page1.vue</li>
  <li>Page2.vue</li>
  </ul>
  
  <p>In both .vue pages I'm using the <code>mounted()</code> instance. In Page1.vue the code starts listening to a socket connection. When I switch to Page2 and back to Page1, it starts listening twice to the socket connection.</p>
  
  <p>I've tested with a simple console.log('Page1.vue') and Page2.vue in page2. When I switch pages, it will console.log multiple times, for each time I switch a page, it will do an extra console.log.</p>
  
  <p>I tried to only execute the code in <code>mounted()</code> instance once, but after switching pages, it doesn't do anything.</p>
  
  <p>How can I take care it only mounts once, or do I need to unmount just before switching page? If so, how can I do that?</p>
  
  <p>Page1.vue and Page2.vue</p>
  
  <pre><code>&lt;template&gt;
    // The template
  &lt;/template&gt;
  &lt;script&gt;
  var socket = io(window.SOCKET_URL, {secure: true});
  
  export default {
  
      mounted(){
          socket.on('channel:listen', function (data) {
              console.log('Page1.vue');
          }
      }
  }
  &lt;/script&gt;
  </code></pre>
  
  <p><strong>Solution</strong></p>
  
  <pre><code>&lt;template&gt;
    // The template
  &lt;/template&gt;
  &lt;script&gt;
  var socket;
  
  export default {
      beforeCreate() {
          socket = io(window.SOCKET_URL, {secure: true});
      },
  
      mounted(){
          socket.on('channel:listen', function (data) {
              console.log('Page1.vue');
          }
      },
  
      beforeDestroy() {
          socket.close();
      },
  }
  &lt;/script&gt;
  </code></pre>